繁体   English   中英

在Ruby on Rails中处理ActiveRecord :: RecordNotFound

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

在我的编辑动作中,我有

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

这样用户只能编辑属于他们商店的商品。 如果他们尝试编辑不属于他们商店的商品,那么他们会收到ActiveRecord :: RecordNotFound错误。

在这种情况下处理此错误的最佳方法是什么? 我应该提出例外吗? 我应该重定向某个地方并设置闪光灯(如果是这样,我该怎么做),我应该保持原样吗? 任何建议表示赞赏。

谢谢

在控制器中添加以下内容:

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

+ @Koraktor的解决方案。 如果要避免使用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

此外,您应该在渲染模板时设置http状态:

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

检查Rails指南 (第2.2.13.4节)以获取状态列表。

如其他地方所述(例如此处 ),在发送40x状态时不应进行重定向,只有30x状态应允许重定向。 因此,每当尝试使用:not_found状态进行重定向时,您可能会遇到一个奇怪的“您正被重定向”页面。

暂无
暂无

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

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