Adn*_*nan 12 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)
现在我要么是否有正确的ID,我总是在我看来"OK",我做错了什么?
我需要在DB中没有ID时显示"ERROR".我也试过使用,rescue ActiveRecord::RecordNotFound但同样的事情发生了.
所有帮助表示赞赏.
shi*_*ara 33
仅当救援块中没有返回时,才解释救援块结束后的所有代码.所以你可以在救援区结束时给退货打电话.
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
Run Code Online (Sandbox Code Playgroud)
要么
def index
@user = User.find(params[:id])
# after is interpret only if no exception before
flash[:notice] = "OK"
redirect_to(:action => 'index')
rescue
flash[:notice] = "ERROR"
redirect_to(:action => 'index')
end
Run Code Online (Sandbox Code Playgroud)
但在你的情况下,更好的是使用rescue_from或rescue_in_public
喜欢
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
Run Code Online (Sandbox Code Playgroud)
但是使用rescue_in_public并不是一个好建议
只是 Rails Rescue 的总体答案:
我发现这非常酷:
@user = User.find(params[:id]) rescue ""
Run Code Online (Sandbox Code Playgroud)