All threads / Pundit scopes

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Pundit scopes

Dmitry Amelchenko asked in General

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)

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.