Search code examples
ruby-on-railsactiverecordpundit

Identifying the right scope joins for pundit


I'm currently implementing pundit, where I am trying to identify whether or not a user has an admin role.

Issue

I'm trying to avoid creating a join_table between discounts and users, by leveraging the relationship between

  • discounts and attraction (a discount belongs to an attraction)
  • attractions and park (a park has_many attractions)
  • parks and users (many to many relationship, via a join_table).

--> However, I get the error message: undefined local variable or method `attraction' for #<DiscountPolicy::Scope:0x00007fa012ec6b70>

Question

I was wondering:

  1. if it's even possible what I'm trying to do and if so
  2. how will I be able to access the user?

Code

discount controller

def index
    @user = current_user
    if params[:attraction_id]
      @attraction = Attraction.find(params[:attraction_id])
      @discounts = @attraction.discounts
      @discounts = policy_scope(@discounts)
    else
      @discounts = []
    end
end

discount policy

class DiscountPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      if user.admin?
        # scope.where(user: user)
        scope.joins(attraction: :discounts).where(discounts: { attraction_id: attraction.id }).joins(park: :attractions).where(attractions: { park_id: park.id }).joins(park: :user_parks).where(user_parks: { user_id: user.id })
      else
        raise Pundit::NotAuthorizedError
      end
    end
  end

  def index?
    user.admin?
  end
end

models

class Discount < ApplicationRecord
  belongs_to :attraction
  has_many :reservations
end

class Attraction < ApplicationRecord
  belongs_to :park
  has_many :discounts, dependent: :destroy
  accepts_nested_attributes_for :discounts, allow_destroy: true
end

class Park < ApplicationRecord
  has_many :attractions, dependent: :destroy
  has_many :discounts, through: :attractions
  has_many :user_parks, dependent: :destroy
  has_many :users, through: :user_parks
  accepts_nested_attributes_for :users, allow_destroy: true, reject_if: ->(attrs) { attrs['email'].blank? || attrs['role'].blank?}
end

class UserPark < ApplicationRecord
  belongs_to :park
  belongs_to :user
end

class User < ApplicationRecord
  has_many :user_parks, dependent: :destroy
  has_many :parks, through: :user_parks
  enum role: [:owner, :admin, :employee, :accountant]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :admin
  end

  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :invitable
end

Solution

  • You need to have nested association joins. Here's what your scope should look like:

    scope.joins(attraction: [park: :user_parks]).where(user_parks: { user_id: user.id })
    

    You can go through the documentation to understand better.