Pundit 政策的嵌套资源

Nested Resources For Pundit Policy

我仍在努力了解 Pundit 政策。我想我很接近,但我浪费了太多时间试图弄清楚这一点。我的帖子政策运行良好,但尝试授权评论时,出现未定义的错误...

comments_controller.rb

class CommentsController < ApplicationController
before_action :find_comment, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:comment))
    @comment.user_id = current_user.id if current_user
authorize @comment
    @comment.save

    if @comment.save
        redirect_to post_path(@post)
    else
        render 'new'
    end
end

def edit
authorize @comment
end

def update
authorize @comment
    if @comment.update(params[:comment].permit(:comment))
        redirect_to post_path(@post)
    else
        render 'edit'
    end
end

def destroy
authorize @comment
@comment.destroy
redirect_to post_path(@post)
end

private

  def find_comment
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
  end
 end

comment_policy.rb

class CommentPolicy < ApplicationPolicy

  def owned
    comment.user_id == user.id
  end

  def create?
    comment.user_id = user.id
    new?
  end

  def new?
    true
  end

  def update?
   edit?
  end

  def edit?
    owned
  end

  def destroy?
    owned
  end
end

格式和缩进有点不对...这不是我发誓的编码方式

  class ApplicationPolicy
    attr_reader :user, :post

    def initialize(user, post)
      raise Pundit::NotAuthorizedError, "must be logged in" unless user
      @user = user
      @post = post
    end

    def index?
      false
    end

    def show?
      scope.where(:id => post.id).exists?
    end

    def create?
      false
    end

    def new?
      create?
    end

    def update?
      false
    end

    def edit?
      update?
    end

    def destroy?
      false
    end

    def scope
      Pundit.policy_scope!(user, post.class)
    end

    class Scope
      attr_reader :user, :scope

      def initialize(user, scope)
        @user = user
        @scope = scope
      end

      def resolve
        scope
      end
    end
  end

您在 ApplicationPolicy 中将资源初始化为 @post。并且由于您的 CommentPolicy 继承自 ApplicationPolicy 并使用其初始化,因此它只能访问 @post。最好的选择是将其保留为 record:

  class ApplicationPolicy
    attr_reader :user, :record

    def initialize(user, record)
      raise Pundit::NotAuthorizedError, "must be logged in" unless user
      @user = user
      @record = record
    end
    ## code omitted
  end

  class CommentPolicy < ApplicationPolicy
    def owned
      record.user_id == user.id
    end
    ## code omitted
  end

基本上你可以随意称呼它,但 record 更有意义,因为它将用于不同的策略子类。