好的,所以我有一个我正在使用的应用程序的方法,它可以在生产中使用。我的问题为什么这有效?这是新的Ruby语法吗?
def edit
load_elements(current_user) unless current_user.role?(:admin)
respond_to do |format|
format.json { render :json => @user }
format.xml { render :xml => @user }
format.html
end
rescue ActiveRecord::RecordNotFound
respond_to_not_found(:json, :xml, :html)
end
答案 0 :(得分:13)
rescue
当它们在方法中时,不需要绑定到显式begin
,这就是定义语法的方式。有关示例,请参阅#19 here和this SO question以及the dupe above。
答案 1 :(得分:2)
救援可以单独工作。不需要始终开始和结束。
当线路上的其他内容出错时,您可以使用单线形式的救援来返回值:
h = { :age => 10 }
h[:name].downcase # ERROR
h[:name].downcase rescue "No name"
答案 2 :(得分:0)
rescue
字是方法定义的一部分
但是在控制器中更好地用rescue_from
答案 3 :(得分:-3)
试试这个
def edit
begin
load_elements(current_user) unless current_user.role?(:admin)
respond_to do |format|
format.json { render :json => @user }
format.xml { render :xml => @user }
format.html
end
rescue ActiveRecord::RecordNotFound
respond_to_not_found(:json, :xml, :html)
end
end