Slinky
Slinky

Reputation: 5832

Handling ActiveRecord Results - No Record Found

How can I prevent my controller from throwing errors when an ActiveRecord query does not return a result?

 ActiveRecord::RecordNotFound in PasswordResetsController#edit
 Couldn't find User with password_reset_token = rqZEGQUH54390Pg-AUC5Q

I thought that the "!" symbol would produce a 404 but at least in development, it displays the error trace in the browser.

Will this method below produce a 404 in production, if the query returns nothing?

If not, how can I fix?

Thanks

    def edit
      @user = user.find_by_password_reset_token!(params[:id])
    end

Upvotes: 0

Views: 538

Answers (2)

sjain
sjain

Reputation: 23344

Try:

 class PasswordResetsController
   def edit
     ...
     begin
      @user = user.find_by_password_reset_token!(params[:id])

     rescue ActiveRecord::RecordNotFound  
      redirect_to :controller => "{Your Controller}", :action => "{Your Action}"
      return
     end
    end
   end

Upvotes: 0

Jon Cairns
Jon Cairns

Reputation: 11951

With the rescue clause:

def edit
  @user = user.find_by_password_reset_token!(params[:id])
rescue ActiveRecord::RecordNotFound => e
  # Do something with error, 'e'
end

Or with rescue_from in the controller (can be reused across multiple actions:

rescue_from ActiveRecord::RecordNotFound, with: lambda do |e|
  # Do something with error, 'e'
end

def edit
  @user = user.find_by_password_reset_token!(params[:id])
end

In answer to your other question, it will give an HTTP 404 error in production but it will not show a stack trace. By default it shows a very basic error page that says something went wrong.

Upvotes: 2

Related Questions