I have a multiple select box for a has_many association. The params come in as:
foo_ids: ["1", "2", "3"]
Using strong parameters, I do not permit this attribute because I would like to authorize it myself so people cannot just put whatever they want in it.
def update
bar.foos = authorized_foos
bar.update(baz_params)
respond_with bar
end
private
def authorized_foos
foos = Foo.find(params[:baz][:foo_ids])
foos.each do |foo|
authorize foo, :manage?
end
end
This approach is going to force me to find all of the foos, loop through them, and authorize each one individually. Is there an easier way to manage has_many authorization, preferably with the Pundit gem?
Pundit is a Ruby gem that handles authorization via a very simple API. Remember that authorization is different from authentication — authentication is verifying that you are who you say you are, and authorization is verifying that you have permission to perform an action.
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 scalable authorization system. Links: API documentation for the most recent version.
Authentication is the process of verifying who you are. Authorization is the process of verifying that you have access to resources.
Pundit creates an instance of class Scope (nested inside the class TaskPolicy) passing along the current_user and the Task model (our scope in this case) as parameters which get set in the @user and @scope instance variables respectively inside the initialize method.
The simplest way to do this is looping. Iterate through each user from the users' array and authorize each and every user. For example,
users_id_array = [1,2,3,4,5,6]
private
def authorized_users
users = User.find(params[:group][:user_ids])
users.each { |u| authorize u, :manage? }
...
end
So this is the very basic and simplest answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With