Home > Software engineering >  How to check class in a policy's scope
How to check class in a policy's scope

Time:07-23

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

  • Tropical < Fruit
  • Temperate < Fruit

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?

CodePudding user response:

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
  • Related