簡體   English   中英

從Rails中的ActiveRecord :: RecordNotFound救援

[英]rescue from ActiveRecord::RecordNotFound in Rails

用戶只能編輯自己的帖子,因此我使用以下內容檢查用戶是否可以輸入編輯表單:

  def edit
    @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Wrong post it"
    redirect_to :action => 'index'
  end

但它不起作用,任何想法我做錯了什么?

如果你想使用rescue語句,你需要以一種引發異常的方式使用find() ,即傳遞你想要查找的id。

def edit
  @post = Load.scoped_by_user_id(session[:user_id]).find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:notice] = "Wrong post it"
  redirect_to :action => 'index'
end

您還可以使用ActionControllerrescue_from方法。 立刻為整個應用程序做!

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  def record_not_found
    render 'record_not_found' # Assuming you have a template named 'record_not_found'
  end
end

事實證明你正在使用救援並且錯誤地找到(:第一個)。

find:如果沒有記錄符合條件,則首先返回nil。 它不會引發ActiveRecord :: RecordNotFound

嘗試

def edit
  @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})
  if @post.nil?
    flash[:notice] = "Wrong post it"
    redirect_to :action => 'index'
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM