Challenge 2: A Pundit Policy — Solution # app/policies/comment_policy.rb class CommentPolicy < ApplicationPolicy def update? user.admin? || record.user == user end def destroy? user.admin? || record.user == user || record.post.user == user end end # app/controllers/comments_controller.rb class CommentsController < ApplicationController def update @comment = Comment.find(params[:id]) authorize @comment # ... end end =begin Notes: - update? allows exactly two groups: admins, or the comment's own author (record.user == user, where record is the Comment being authorized and user is the current logged-in user, both supplied automatically by Pundit). - destroy? is more permissive, adding a third allowed group: the post's own author, via record.post.user == user -- reflecting the reasonable real-world rule that whoever owns a post should be able to moderate comments on it, even ones they didn't personally write. - authorize @comment in the controller looks up CommentPolicy automatically from @comment's class name, and calls update? because the current action is update -- no manual wiring beyond that one line. - If update? returns false, authorize raises Pundit::NotAuthorizedError, caught by the rescue_from declared once in ApplicationController (Chapter 2's earlier example) rather than needing its own error handling written here. =end