Rai*_*ner 19 ruby-on-rails ruby-on-rails-3
如果找不到记录,我正在尝试重定向.该页面不是重定向,我得到错误记录未找到.
我的控制器:
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
Run Code Online (Sandbox Code Playgroud)
Eri*_*ang 36
我一直在做的是把这个放在方法的最后:
rescue ActiveRecord::RecordNotFound
redirect_to root_url, :flash => { :error => "Record not found." }
Run Code Online (Sandbox Code Playgroud)
更好的是,将它作为控制器的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
Run Code Online (Sandbox Code Playgroud)
错误是由Link.find生成的 - 如果找不到对象,它会引发异常
你可以简化你的代码:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14874 次 |
| 最近记录: |