我的毁灭?和upvote?即使我已授权他们,也不与Pundit合作的方法

问题描述 投票:0回答:2

我刚在我的应用上安装了Pundit。我已设法为新的创建和显示方法实现权威,但是当涉及到我的销毁和向上投票方法时,我得到以下错误Pundit::NotDefinedError in HairstylesController#upvote unable to find policy `NilClassPolicy` for `nil

这是我的回购,以便在需要时理解: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

pundit policy.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文件upvote html(在我添加权威之前有效)

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

我希望用户能够在发型上投票,我希望用户能够删除他们的hairstlye。

ruby-on-rails ruby pundit
2个回答
2
投票

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

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

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

0
投票

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

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

Pundit::NotAuthorizedError in HairstylesController#upvote not allowed to upvote? this... #<是因为而不是:

def upvote? record.user == user end

在我的upvote政策?方法,

我应该这样说:

def upvote? return true end

© www.soinside.com 2019 - 2024. All rights reserved.