【发布时间】:2012-10-29 22:38:14
【问题描述】:
我的控制器中有 2 种方法用于查找用户(注意 enabled_only 范围):
before_filter :find_user, :only => :show
before_filter :find_any_user, :only => [:edit, :update, :destroy]
def find_user
@user = User.enabled_only.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
def find_any_user
@user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
当然,这些可以合并为一种方法来检查:action == 'show' 是否存在,但我无法通过救援来捕获错误。我尝试了以下类似的方法,但没有成功:
before_filter :find_user, :only => [:show, :edit, :update, :destroy]
def find_user
@user = if :action == 'show'
User.enabled_only.find(params[:id])
else
User.find(params[:id])
end
rescue ActiveRecord::RecordNotFound
flash[:alert] = "The user you were looking for could not be found"
redirect_to root_path
end
请告知如何做到这一点。
谢谢
【问题讨论】:
标签: ruby-on-rails-3 controller before-filter rescue