![](/img/trans.png)
[英]ActiveRecord#exists? or rescue from 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
您还可以使用ActionController
的rescue_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.