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