4

我的控制器中有 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

请告知如何做到这一点。

谢谢

4

1 回答 1

4

您需要将要“保护”的代码包装在 abegin和 a之间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"

于 2012-10-29T22:45:26.567 回答