用 Pundit Policy 管理 permitted parameters、預設值與各 action 的參數
February 10, 2022
要管理 permitted params,你可以在你的 policy 中加入 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
然後在你的 controller 裡
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