Ruby on rails 铁路救援工作
我正在处理下面的作品Ruby on rails 铁路救援工作,ruby-on-rails,ruby,rescue,Ruby On Rails,Ruby,Rescue,我正在处理下面的作品 def index @user = User.find(params[:id]) rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') else flash[:notice] = "OK" redirect_to(:action => 'index') end 现在,无论我是否有正确的身份证,我总是在我看来“OK”,我做错了什么 我需要在D
def index
@user = User.find(params[:id])
rescue
flash[:notice] = "ERROR"
redirect_to(:action => 'index')
else
flash[:notice] = "OK"
redirect_to(:action => 'index')
end
现在,无论我是否有正确的身份证,我总是在我看来“OK”,我做错了什么
我需要在DB中没有ID时显示“错误”。我也尝试过使用营救ActiveRecord::RecordNotFound
,但同样的情况也发生了
感谢所有的帮助 如果没有具有该
id
的user
,则user.find
将返回nil
。返回nil
不是错误情况,并且不会触发rescue
只有在rescue块中没有返回时才会解释rescue块结束后的所有代码。所以你可以在营救区结束时呼叫return
def index
begin
@user = User.find(params[:id])
rescue
flash[:notice] = "ERROR"
redirect_to(:action => 'index')
return
end
flash[:notice] = "OK"
redirect_to(:action => 'index')
end
或
但在你的情况下,最好是使用或
像
class UserController'index')
结束
def索引
@user=user.find(参数[:id])
闪光[:注意]=“确定”
将_重定向到(:action=>'index')
结束
结束
但在公众场合使用rescue并非真正的好建议仅仅是一个全面的Rails rescue答案: 我觉得这很酷:
@user = User.find(params[:id]) rescue ""
我很肯定这是不对的<代码>查找具有无效ID的将引发
ActiveRecord::RecordNotFound
。如果使用一个动态查找程序,例如User.find by_name
,其值与记录不匹配,则返回nil
。好吧,先生,我查过了,你是对的。非常感谢。OP中的find调用实际上应该引发,除非代码实际上是User.find(:first,params[:id])
。这是应用程序中的实际代码吗?目前看来,您正在重定向回相同的操作(索引),这将导致一个无限循环。
class UserController < ApplicationController
def rescue_in_public(exception)
flash[:notice] = "ERROR"
redirect_to(:action => 'index')
end
def index
@user = User.find(params[:id])
flash[:notice] = "OK"
redirect_to(:action => 'index')
end
end
@user = User.find(params[:id]) rescue ""