Ask A Question

Notifications

You’re not receiving notifications from this thread.

Pundit: How to apply the same policy to nested resources

Adrien Nhem asked in General

working with pundit gem. Is it possible to apply the same rule to nested resources? if show is not allowed in lecture_policy then show in lesson_policy should not be allowed too.

Lecture
    has_many :enrollments
    has_many :users, through: :enrollments
   has_many :lessons
end

Lesson
    belongs_to :lecture
end

User
   has_many :lectures, through: enrollments
   has_many :enrollments
end

Enrollment
    belongs_to :user
    belongs_to :lecture
end

LecturePolicy

class LecturePolicy < ApplicationPolicy
    def index?
        true
    end

    def create?
        false
    end

    def update?
        false
    end

    def edit?
        false
    end

     class Scope < Scope
        def resolve
            scope.where(:id => user.enrollments.select(:lecture_id))
        end
      end

end

Thanks so much for your comments!

Reply

The answer is simple enough that you might kick yourself. :)

You can simply call the policy inside the other one. Here's an example I found on Stack Overflow:

def edit?
  # I am assuming that a user can edit themselves, so the "or" is in there, if not, go back to using and
  document.user_id == user.id or UserPolicy.new(user, User.find(document.user_id)).edit?
end

http://stackoverflow.com/questions/26514769/nested-pundit-policies

Reply

I kicked myself! haha

Actually I have found the answer, I must have been really tired....

What I did is that I just added to the lessons_controller.rb seems to do the trick actually. Will run some test.

  def show
    @lecture = Lecture.find(params[:lecture_id])
    @lesson = @lecture.lessons.find(params[:id])
    **authorize @lecture**
  end
Reply

That will work! :)

Reply
Join the discussion
Create an account Log in

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

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

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