简体   繁体   English

在Ruby on Rails中处理ActiveRecord :: RecordNotFound

[英]Handling ActiveRecord::RecordNotFound in Ruby on Rails

In my edit action, I have 在我的编辑动作中,我有

@item = current_user.shop.items.find(params[:id])

So that the user can only edit items that belong to their shop. 这样用户只能编辑属于他们商店的商品。 If they try to edit an item that does not belong to their shop, then they get an ActiveRecord::RecordNotFound error. 如果他们尝试编辑不属于他们商店的商品,那么他们会收到ActiveRecord :: RecordNotFound错误。

What is the best way of handling this error in situations like this? 在这种情况下处理此错误的最佳方法是什么? should i raise an exception? 我应该提出例外吗? should i redirect somewhere and set the flash (if so, how do i do that), should i just leave it as is? 我应该重定向某个地方并设置闪光灯(如果是这样,我该怎么做),我应该保持原样吗? Any advice is appreciated. 任何建议表示赞赏。

Thanks 谢谢

Add something like the following to your controller: 在控制器中添加以下内容:

rescue_from ActiveRecord::RecordNotFound do
  flash[:notice] = 'The object you tried to access does not exist'
  render :not_found   # or e.g. redirect_to :action => :index
end

+1 for the solution of @Koraktor. + @Koraktor的解决方案。 If you want to avoid ActiveRecord::RecordNotFound, you can use find_by method instead of find. 如果要避免使用ActiveRecord :: RecordNotFound,可以使用find_by方法而不是find。

@item = current_user.shop.items.find_by_id(params[:id])
if @item.nil?
  flash[:error] = "Item not found"
else
  # Process the @item...
end

Additionally you should set the http status while rendering the template : 此外,您应该在渲染模板时设置http状态:

rescue_from ActiveRecord::RecordNotFound do
  render :not_found, :status => :not_found
end

Check the Rails guide (section 2.2.13.4) for the status list. 检查Rails指南 (第2.2.13.4节)以获取状态列表。

As stated somewhere else (for example here ) you should never make a redirection when sending a 40x status, only 30x statuses should allow redirecting. 如其他地方所述(例如此处 ),在发送40x状态时不应进行重定向,只有30x状态应允许重定向。 So you may encounter a weird "You are being redirected" page whenever trying to make a redirect with a :not_found status. 因此,每当尝试使用:not_found状态进行重定向时,您可能会遇到一个奇怪的“您正被重定向”页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM