【问题标题】:my destroy? and upvote? methods not working with Pundit even though I have authorised them我的毁灭?并投票?即使我已授权,方法也无法与 Pundit 一起使用
【发布时间】:2019-04-28 13:04:42
【问题描述】:

我刚刚在我的应用程序上安装了 Pundit。我已经设法为新的 create 和 show 方法实现 pundit,但是当涉及到我的 destroy 和 up vote 方法时,我收到以下错误Pundit::NotDefinedError in HairstylesController#upvote unable to find policy `NilClassPolicy` for `nil

这里是我的 repo,以便在需要时便于理解:https://github.com/Angela-Inniss/hair-do

我已经在我的控制器中授权了两种方法,“upvote”和“destroy”。我已经更新了相关政策。请看下面的代码。

带有相关方法的控制器:

  def destroy
    authorize @hairstyle
    @hairstyle = Hairstyle.find(params[:id])
    @hairstyle.destroy
    redirect_to hairstyles_path
  end

  def upvote
    authorize @hairstyle
    @hairstyle = Hairstyle.find(params[:id])
    @hairstyle.upvote_from current_user
    redirect_to hairstyles_path
  end

权威策略.rb 文件:


  def upvote?
    record.user == user
    # - record: the restaurant passed to the `authorize` method in controller
    # - user:   the `current_user` signed in with Devise.
  end

  def destroy?
    record.user == user
  end

index.html.erb 文件销毁 html

 <% if policy(hairstyle).destroy? %>
              <p><%= link_to "Delete", hairstyle_path(hairstyle),method: :delete, data: { confirm: "Are you sure?" }%></p>
           <% end %>

index.html.erb 文件支持 html(在我添加 pundit 之前有效)

   <%= link_to like_hairstyle_path(hairstyle), method: :put do %>
               <i class="fa fa-heart">
                <span><%= hairstyle.get_upvotes.size %><span>
               </i>
            <% end %>

我希望用户能够为发型投票 我希望用户能够删除他们的头发。

【问题讨论】:

    标签: ruby-on-rails ruby pundit


    【解决方案1】:

    你不应该在设置对象之后调用authorize 吗?尝试离开

    authorize @hairstyle
    @hairstyle = Hairstyle.find(params[:id])
    

    @hairstyle = Hairstyle.find(params[:id])
    authorize @hairstyle
    

    【讨论】:

    • 我正要这么说。发型为 nil,它使用您尝试授权的事物的类作为策略类(HairstylePolicy、NilClassPolicy)。
    • 我尝试了你所说的删除方法,但它工作了但是对于 upvote 方法我将授权更改为 AFTER 对象设置然后单击我网站上的 upvote 我收到此错误Pundit::NotAuthorizedError in HairstylesController#upvote not allowed to upvote? this... #&lt; 这很奇怪因为如您所见,我已授权该方法:S 有什么想法吗?
    【解决方案2】:

    您好,我的问题已解决。 部分原因是,正如你们在上面所说的那样,我在设置对象后应该在错误的地方调用授权。

    接下来我收到错误的原因:

    Pundit::NotAuthorizedError in HairstylesController#upvote not allowed to upvote? this... #&lt; 是因为没有放:

    def upvote? record.user == user end

    在我的投票政策中?方法,

    我应该这样写的:

    def upvote? return true end

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2011-11-15
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多