我的控制器中有两个方法可以找到用户(注意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
请告知如何做到这一点。
由于
答案 0 :(得分:4)
您需要在begin
和rescue
before_filter :find_user, :only => [:show, :edit, :update, :destroy]
def find_user
begin
@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
end
顺便说一句,你的测试:action == 'show'
永远不会成真。 :action
是一个符号,其值为:action
,其值永远不会改变,'show'
相同,其值永远不会改变。我不确定实现这一目标的最佳方式是什么,但你可以这样做,但你可以做if params[:action] == "show"