Rails异常不适用于find_by查询

时间:2015-05-22 11:58:18

标签: ruby-on-rails ruby

异常处理不适用于rails中的find_by查询   这里是代码:

  ab = User.find_by_uniq_token(params[:uniq_token])

不提出例外......同时:

  ab = User.find(:id)  # is working fine...

我在应用程序控制器中有异常处理代码,如:

  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found


  def record_not_found
    if current_user
      flash[:notice] = "Record not found "
      redirect_to authenticated_root_url
   else
     flash[:notice] = "Record not found ."
     redirect_to unauthenticated_root_url
     # Assuming you have a template named 'record_not_found'
   end
 end

1 个答案:

答案 0 :(得分:2)

如果没有找到记录,您需要使用等效的bang(!)方法来引发异常。

ab = User.find_by_uniq_token!(params[:uniq_token])

ab = User.where(uniq_token: params[:uniq_token]).first!