从 Rails 中的 ActiveRecord::RecordNotFound 救援 [英] rescue from ActiveRecord::RecordNotFound in Rails

查看:23
本文介绍了从 Rails 中的 ActiveRecord::RecordNotFound 救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户只能编辑自己的帖子,因此我使用以下内容来检查用户是否可以输入编辑表单:

A user can only edit its own post, so I use the following to check if a user can enter the edit form:

  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

但它不起作用,知道我做错了什么吗?

But it is not working, any ideas what I am doing wrong?

推荐答案

如果你想使用rescue语句你需要使用find() 以一种它引发异常的方式,即传递您要查找的 ID.

If you want to use the rescue statement you need to use find() in a way it raises exceptions, that is, passing the id you want to find.

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

这篇关于从 Rails 中的 ActiveRecord::RecordNotFound 救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆