Pundit scopes
Hi, i have no idea how to choose best way. There are three models User, Department and Task. Each user assigned to one department (belongs to). Department has many tasks. How to write a policy or something to do without using Pundit, when user can see only tasks from assigned department?
Dmitry,
Without Pundit, you can scope your queries in the controller with @tasks = current_user.department.tasks so that it always accesses them through the User.
With Pundit, you can setup a scope to reference the Department on the user:
class TaskPolicy < ApplicationPolicy
class Scope < TaskPolicy
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
@scope.where(department_id: @user.department_id)
end
end
end
And use this by saying @tasks = policy_scope(Task)
It sounds like you're trying to implement a role-based access control system for your application. You can achieve this by creating a simple method that checks the user's department before displaying tasks. This way, users will only see tasks relevant to their department, ensuring data privacy. For more tips on enhancing your project, check out wheelie party for great resources and community support!