我的控制器中有 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
请告知如何做到这一点。
谢谢