leejay100
leejay100

Reputation: 221

Rails Custom Error Pages with Custom Routes

I'm following this tutorial: http://wearestac.com/blog/dynamic-error-pages-in-rails

However, in my routes file, I have two custom routes:

get '/blog',        to: 'blog_posts#index', as: :blog
get '/:id',         to: 'blog_posts#show', as: :show_blog_post

When I go to a page that doesn't exist, it isn't redirecting to the error pages. Instead, it's giving me Completed 404 Not Found. Error during failsafe response: ActiveRecord::RecordNotFound.

The custom routes are somehow not making the error pages work. When I remove the custom routes, everything works fine.

How do I get my error pages to work with this? I would've thought that anything returning a 404 would be redirect to the ErrorsController, but that isn't happening.

Upvotes: 0

Views: 158

Answers (1)

Adib Saad
Adib Saad

Reputation: 572

Your

get '/:id', to: 'blog_posts#show', as: :show_blog_post

route seems to be picking up your custom error handling. If a user goes to

/404

the blog_posts#show gets called with the parameter id = 404, and I'm guessing it's trying to look up a blog post with an id of 404 which results in ActiveRecord::RecordNotFound exception.

What you can do is place your error rules at the top, before /:id, since routes get matched in the order that they're listed, but I'd just recommend not using something like /:id since it can accidentally pick things up, like what we're dealing with. Scope the route with something descriptive like /posts/:id.

Upvotes: 1

Related Questions