簡體   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