Pundit Pearl Identity Array Authorization

I have a multiple select box for the has_many association. The parameters are:

foo_ids: ["1", "2", "3"] 

Using strong parameters, I do not allow this attribute, because I would like to authorize it myself, so that people can’t just put what they need in them.

 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 will make me find all foos, skip them and allow each one separately. Is there an easier way to manage has_many authorization, preferably with a Pundit stone?

+8
ruby-on-rails ruby-on-rails-4 strong-parameters pundit
source share
2 answers

The easiest way to do this is through a loop. Iterate through each user from an array of users and authorize each 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 simplest and easiest answer.

+1
source share

I am doing something similar to this. Due to the little information you provide, I am going to make a number of assumptions.

  • You have a lot in common for foos users. By this, I mean that foo can have many users, and a user can be a member of many foos.

  • You understand how to set up models to achieve (1). If you are not just commenting, and I will edit this answer.

So we will need to work for this to work, this is the following:

  • @foo.users returns a collection of users
  • @user.foos returns foos collection

Using models configured to support the above actions is much easier than you do.

 class FooPolicy < ApplicationPolicy class Scope < Scope def resolve user.foos end end end 

I think you are missing an expert point. Pundit allows you to do user authorization by user. Thus, the above code allows the user to use only the groups (foos in this case) that are part of.

0
source share

All Articles