mechnicov
mechnicov

Reputation: 15372

How can I bypass error ActiveRecord::RecordNotFound?

That's my files:

routes.rb

...
resources :users
...

users_controller.rb

...
def show
  @user = User.find(params[:id])
end
...

show.html.erb

<% provide(:title, @user.name) %>
...

For example, I haven't user with 'id'=20.

Of course, if go to users/20 it will be ActiveRecord::RecordNotFound

I tried @user = User.find_by(id: params[:id]). But it's not good idea, because of ERB

I would like to redirect to root_url and make flash[:danger] for example.

How could I solve this problem?

Upvotes: 0

Views: 359

Answers (2)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

Unlike the generic rescue_from, something like this would allow you to handle different actions in one controller in different ways.

def show
  unless @user = User.find_by(params[:id])
    flash[:danger] = "watch out"
    redirect_to root_path
  end
end

Upvotes: 2

Alex Suslyakov
Alex Suslyakov

Reputation: 2232

You can use rescue_from for this case. It's a pretty common approach

rescue_from ActiveRecord::RecordNotFound, with: -> { render status: :not_found, nothing: true }

You might like to render 404 or make a redirect

Upvotes: 2

Related Questions