我刚刚在我的应用程序上安装了Pundit。我已经设法为新的create和show方法实现了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文件支持html(在我添加pundit之前起作用)
<%= link_to like_hairstyle_path(hairstyle), method: :put do %>
<i class="fa fa-heart">
<span><%= hairstyle.get_upvotes.size %><span>
</i>
<% end %>
我希望用户能够对发型进行投票 我希望用户能够删除其发型。
答案 0 :(得分:2)
设置对象后,您不应该呼叫authorize
吗?尝试离开
authorize @hairstyle
@hairstyle = Hairstyle.find(params[:id])
到
@hairstyle = Hairstyle.find(params[:id])
authorize @hairstyle
答案 1 :(得分:0)
你好,我解决了我的问题。 一部分原因是,正如您在上面提到的那样,我在错误的位置调用了授权,而该错误应该在设置对象之后发生。
接下来我得到错误的原因:
Pundit::NotAuthorizedError in HairstylesController#upvote not allowed to upvote? this... #<
是因为没有放置:
def upvote?
record.user == user
end
我应该放这个:
def upvote?
return true
end