I recently started using the Pundit gem for authorization in my Rails app. In my app I have models for Company
, each Company
can have multiple Employees
, this is done through a has many through relationship:
# company.rb
has_many :employees, dependent: :destroy
has_many :users, through: :employees
# employee.rb
belongs_to :company
# user ...
Employees
can either be published or not published. In my view for listing company employees, I want to only display published
employees for regular users, but other employees of a given company should see all employees for that company.
In my employees_controller#index
I have a solution that currently looks like this:
def index
@employees = if current_user.is_employee?(@company)
@company.employees.all
else
@company.employees.select { |employee| employee.published == true }
end
end
This works, but I'm trying to understand how to utilise Pundit
s scopes to achieve the same.
Pseudo code for a Pundit Scope (that's clearly not working, but gives an example of what I want to achieve):
# EmployeePolicy
class Scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.is_employee?(...) # can't get company from scope
scope.all
else
scope.where(published: true)
end
end
end
I've seen some examples of using joins to achieve this, but that seems a bit cumbersome, is there some other recommended way to achieve this using Pundit?