-
I'm using the ActionController parameters feature. I'd like to be able to query which params are allowed to the current user, in order to decide which form fields to display in my admin panel. With Pundit I would do something like: - if @post.permitted_attributes.include?(:title)
= f.text_field :title What would be the easiest way to achieve this with ActionPolicy? Thanks! |
Beta Was this translation helpful? Give feedback.
Answered by
palkan
Aug 2, 2022
Replies: 1 comment 2 replies
-
I would suggest using a plain old Ruby method in the policy class for that: class PostPolicy < ApplicationPolicy
def permitted_attributes
%i[title]
end
def permitted_attribute?(name)
permitted_attributes.include?(name)
end
# you can re-use this method in the params scope
params_filter { _1.permit(*permitted_attributes) }
end
# in your view
- if policy_for(@post).permitted_attribute?(:title)
= f.text_field :title Alternatively, you can use scopes (if you need different contexts): class UserPolicy < ApplicationPolicy
scope_for :permitted_params do
%i[name email]
end
scope_for :permitted_params, :update do
%i[name]
end
end
authorized_scope(user, type: :permitted_params)
authorized_scope(user, type: :permitted_params, as: :update) This variant is more verbose (and doesn't reads well), though could be wrapped into a custom API. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
Spone
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would suggest using a plain old Ruby method in the policy class for that:
Alternatively, you can use scopes (if you need different contexts):