我刚刚在我的应用程序上安装了Pundit。我已经设法为新的创建和显示方法实现了Pundit::NotDefinedError in HairstylesController#upvote unable to find policy `NilClassPolicy` for `nil
,但是当涉及到销毁和向上投票方法时,我得到了以下错误pundit
如果需要,为了便于理解,下面是我的存储库: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 (在我添加pundit之前,它是有效的)
<%= link_to like_hairstyle_path(hairstyle), method: :put do %>
<i class="fa fa-heart">
<span><%= hairstyle.get_upvotes.size %><span>
</i>
<% end %>
我希望用户能够向上投票的发型,我希望用户能够删除他们的头发。
发布于 2019-04-28 21:13:04
在设置完对象之后,你不应该调用authorize
吗?尝试从
authorize @hairstyle
@hairstyle = Hairstyle.find(params[:id])
至
@hairstyle = Hairstyle.find(params[:id])
authorize @hairstyle
发布于 2019-04-29 06:10:51
你好,我解决了我的问题。部分原因是,正如你们在上面所说的,我在错误的位置调用了authorize,它应该是在设置对象之后调用的。
接下来是我得到这个错误的原因:
Pundit::NotAuthorizedError in HairstylesController#upvote not allowed to upvote? this... #<
是因为不是放入:
def upvote? record.user == user end
在我的赞成票政策中?方法,
我应该这么说的:
def upvote? return true end
https://stackoverflow.com/questions/55890551
复制相似问题