如果找不到记录,Rails如何重定向

如果找不到记录,我正在尝试重定向。 页面没有重定向,我得到错误记录未找到。

我的控制器:

def index @link = Link.find(params[:id]) respond_to do |format| if @link.blank? format.html { redirect_to(root_url, :notice => 'Record not found') } else format.html { render :action => "index" } end end end 

我一直在做的是把这个放在方法的最后:

 rescue ActiveRecord::RecordNotFound redirect_to root_url, :flash => { :error => "Record not found." } 

更好的是,将它作为控制器的around_filter:

 around_filter :catch_not_found private def catch_not_found yield rescue ActiveRecord::RecordNotFound redirect_to root_url, :flash => { :error => "Record not found." } end 

错误是由Link.find生成的 – 如果找不到对象,它会引发exception

你可以简化你的代码:

 def index @link = Link.find_by_id(params[:id]) redirect_to(root_url, :notice => 'Record not found') unless @link respond_to do |format| format.html end end 

您处于正确的轨道上,只需捕获RecordNotFoundexception:

 def index @link = Link.find(params[:id]) # should render index.html.erb by default rescue ActiveRecord::RecordNotFound redirect_to(root_url, :notice => 'Record not found') end 

非常棘手的…我找到了一个简单的解决方案….这个解决方案适合我

@link = Link.where(:id => params [:id])。首先

我正在使用.first因为.where将返回一个数组。当然,这个数组只有一个元素。 所以,当没有带有这样的id的记录时,它将返回一个空数组,为@link分配一个空元素…现在检查@link是空白还是不…

结论:不需要为简单的检查提供exception处理它是.find的问题它在没有记录存在时抛出exception…使用.where它将返回一个空数组

抱歉我的英语不好

我更喜欢使用find_by。 find_by将找到与指定条件匹配的第一条记录。 如果未找到记录,则返回nil,但不会引发exception,以便您可以重定向到其他页面。

 def index @link = Link.find_by(id: params[:id]) redirect_to(root_url, :notice => 'Record not found') unless @link end