Pundit政策的嵌套资源

时间:2017-09-19 03:57:55

标签: ruby-on-rails pundit

我仍然试图围绕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

1 个答案:

答案 0 :(得分:0)

您在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更有意义,因为它将在不同的策略子类中使用。