【Rails】雑多なメモ
知らないメソッドが色々ありすぎて、忘れそうなのでメモしていきます。
protect_from_forgery with: :exception
# Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception
protect_from_forgery | Railsドキュメント
protect_from_forgery with: :exception
このコードがあると、Railsで生成されるすべてのフォームとAjaxリクエストにセキュリティトークンが自動的に含まれます。セキュリティトークンがマッチしない場合には例外がスローされます。クロスサイトリクエストフォージェリ (CSRF)
この攻撃方法は、ユーザーによる認証が完了したと考えられるWebアプリケーションのページに、悪意のあるコードやリンクを仕込むというものです。そのWebアプリケーションへのセッションがタイムアウトしていなければ、攻撃者は本来認証されていないはずのコマンドを実行できてしまいます。
Rails セキュリティガイド - Railsガイド
helper_method
def current_site @current_site ||= Site.first end helper_method :current_site
helper_method (AbstractController::Helpers::ClassMethods) - APIdock
コントローラー内のメソッドをヘルパーとして宣言する。
viewでもこのメソッドが使えるようになる。
gem pundit
認可に使用する。
ユーザーによってできることを限定したり、許可したりするのに使う。
Pundit provides a set of helpers which guide you in leveraging regular Ruby classes and object oriented design patterns to build a simple, robust and scaleable authorization system.
File: README — Documentation for pundit (2.1.0)
class ApplicationController < ActionController::Base include Pundit (略) end
Pundit is focused around the notion of policy classes. We suggest that you put these classes in app/policies. This is a simple example that allows updating a post if the user is an admin, or if the post is unpublished:
class PostPolicy attr_reader :user, :post def initialize(user, post) @user = user @post = post end def update? user.admin? or not post.published? end end
slug
位置を示すコード
URLの末尾
ユーザーフレンドリーになるように、URLを文字列型にする。
以下のstackoverflowの回答が分りやすかった。
It's simply a way to create user-friendly URLs: