Search code examples
ruby-on-railspundit

Pundit: Proper way to gain access based on joiner table


A bit new to Pundit. I have 3 models and a joiner table; a User, Customer and Route model, and a joiner table that allows users to have a route. Customers belongs to specific routes.

I just want authorize a user to see a customer if she/he has a route in the routes_users joiner table.

I found myself a lot of ways to do that. But, what the best way to achieve it?

customer_policy.rb

def show?
  if user.admin? || user.sales_manager?
    true
  else
    user.routes.map(&:id).include? record.route_id
  end
end

Solution

  • Using .map is not a good idea as it will populate all routes from DB in order to search through them locally, the best is to use .where and not .map as below:

    def show?
      if user.admin? || user.sales_manager?
        true
      else
        user.routes.where(record.route_id).count > 0
      end
    end