如果找不到记录,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
您处于正确的轨道上,只需捕获RecordNotFound
exception:
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
- 如何调用所有评论的post(在这种情况下为锻炼),其中exercise.user_id == current_user.id?
- 如何更改“设计:密码重置指令电子邮件的主题”
- 如何使用devise_token_auth和ActionCable来validation用户?
- 如何使用工厂女孩和黄瓜创建用户记录?
- Rails:.m4v文件的MIME类型问题
- Heroku上的免费SSL安全证书?
- NoMethodError at / undefined方法`name’代表nil:NilClass
- ActiveRecord Association选择包含记录的计数
- rspec测试结果Capybara :: ElementNotFound