Ruby on rails Rails:如何解决:PostsController#show中的Pundit::NotDefinedError?

Ruby on rails Rails:如何解决:PostsController#show中的Pundit::NotDefinedError?,ruby-on-rails,ruby,Ruby On Rails,Ruby,每当我运行以下程序并尝试以任何用户的身份查看我的帖子(在我的show view中),我都会被介绍到这个错误页面: Pundit::NotDefinedError in PostsController#show unable to find policy of nil def show @post = Post.find(params[:id]) authorize @posts # <- The error highlights this

每当我运行以下程序并尝试以任何用户的身份查看我的帖子(在我的show view中),我都会被介绍到这个错误页面:

Pundit::NotDefinedError in PostsController#show
unable to find policy of nil
def show
    @post = Post.find(params[:id])
    authorize @posts                 # <- The error highlights this line
  end
在该错误页面中:

Pundit::NotDefinedError in PostsController#show
unable to find policy of nil
def show
    @post = Post.find(params[:id])
    authorize @posts                 # <- The error highlights this line
  end
邮政政策

    class PostPolicy < ApplicationPolicy
      class Scope < Scope
        def resolve
          if user.admin?
            scope.all
          else
            scope.where(:published => true)
          end
        end

      def index?
        true
      end

      def show?
        true
      end
      def update?
        user.admin? or not post.published?
      end
    end
    end
类后策略true)
结束
结束
def索引?
真的
结束
def秀?
真的
结束
def更新?
user.admin?还是不发表?
结束
结束
结束
索引视图

    <h1>All Posts</h1>

    <% if policy(Post.new).create? %>
    <%= link_to "New Post", new_post_path, class: 'btn btn-success' %>
    <% end %>

    <% @posts.each do |post| %>
      <div class="media">
          <div class="media-body">
            <h4 class="media-heading">
              <%= link_to post.title, post %>
            </h4>
            <small>
              submitted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.name unless post.user.nil? %><br>
              <%= post.comments.count %> Comments
            </small>
        </div>
    </div>
    <% end %>
所有帖子
由
评论
显示视图

<h1> <%= @post.title %> </h1>

<% if policy(@post).edit? %>
<%= link_to "Edit", edit_post_path(@post), class: 'btn btn-success' %>
<% end %>

<p> <%= @post.body %> </p>


提前谢谢大家。如果还有更多信息,请告诉我。

@posts
nil
在show action中,您应该使用
@post

authorize @post

我在使用Punditgem开发只支持API的Rails 6应用程序时遇到了这个问题

当我测试控制器操作的权威授权时,我遇到以下错误:

Pundit::NotDefinedError-找不到零的策略

以下是我解决问题的方法

控制器中的
authorize
方法调用的实例变量必须与正在调用的控制器操作的实例变量相对应

因此,对于
索引
操作,它应该是
@posts

authorize @posts
对于
show
操作,它应该是
@post

authorize @post
对于
create
操作,它应该是
@post

authorize @post
等等

就这些

我希望这有帮助

authorize @post
authorize @post