[英]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.