ruby-on-railsrubyclasspolicypundit

How to check class in a policy's scope


Project is with Rails + Pundit. Fruit class has two subclasses:

In fruit_policy.rb I got this:

class Scope < Scope
    def resolve
      if user.is_near_equator
        scope.where(class: Tropical)
      else
        scope.where(class: Temperate)
      end
    end
  end

The class check above gives me:

NameError (uninitialized constant Fruit::Tropical...
_________________________________________^^^^^^^^^

Is it possible to check the class within a scope in a policy? If so, how?


Solution

  • When you implemented the subclasses with STI and followed Rails naming conventions for database columns then you can scope the query to a subclass by filtering on the type columns with the desired class name as a string:

    def resolve
      if user.is_near_equator
        scope.where(type: 'Fruit::Tropical')
      else
        scope.where(type: 'Fruit::Temperate')
      end
    end