Punditポリシーで許可パラメータをデフォルトとアクション別に管理する
2022年2月10日
許可パラメータを管理するには、ポリシーに permitted_attributes と permitted_attributes_for_#{action} を追加します。例:
class CommentPolicy < ApplicationPolicy
def permitted_attributes
%i[body]
end
def permitted_attributes_for_create
%i[body application_id]
end
end
そしてコントローラーでは次のようにします
class CommentController
def create
@comment = Comment.create(comment_attributes) # { body: 'body', application_id: 1 }
end
def update
@comment = Comment.find(params[:id])
@comment.update(comment_attributes) # { body: 'new body' }
end
private def comment_attributes
permitted_attributes(Comment)
end
end