Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Pundit: How to apply the same policy to nested resources

General • Asked by Adrien Nhem

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!


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


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

That will work! :)


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 29,763+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.