在Ruby on Rails中处理ActiveRecord :: RecordNotFound

pin*_*ngu 6 activerecord ruby-on-rails find ruby-on-rails-3

在我的编辑动作中,我有

@item = current_user.shop.items.find(params[:id])
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Kor*_*tor 22

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

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
Run Code Online (Sandbox Code Playgroud)


Blu*_*ith 20

+ @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
Run Code Online (Sandbox Code Playgroud)


dem*_*tal 5

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

rescue_from ActiveRecord::RecordNotFound do
  render :not_found, :status => :not_found
end
Run Code Online (Sandbox Code Playgroud)

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

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