Never Configure Routes That Aren’t Being Used

Learn about which routes we should not configure in a Rails application.

Why shouldn’t we use bin/rails routes?

Running bin/rails routes on an app is a great way to get a sense of its size, scope, and purpose. If the output of that command lies as ours currently does, it’s not helpful. It creates confusion. More than that, it allows us to use a URL helper that will happily create a route that will never work.

Using the only: parameter

The solution is to use the optional only: parameter to resources. This parameter takes an array of actions that we intend to support. Doing this ensures that if we try to create a route we don’t support using a URL helper, we get a nice NameError (as opposed to a URL that will generate a 404). We mistype URL helpers all the time, and it’s much nicer to find out about this mistake locally with a big error screen than to scratch our heads wondering why we are getting a 404 for a feature we just implemented.

A nice side effect of explicitly listing our actions with only: is that bin/rails routes provide a clean and accurate overview of our app. It lists out the important nouns related to our app and what it does, and this can be a nice starting point for building new features or bringing a new developer onto the team.

This might not seem like a big win for a small app, but remember, we’re setting the groundwork for our app to grow. If we start off using resources and adopt the use of only: when our app gets larger, we will have needless inconsistency and confusion. Thus, we create another decision developers have to make when creating routes: Do we use only: or not?

Even the Rails Guide tells us to avoid creating nonexistent routes if our app has a lot of them:

Get hands-on with 1200+ tech skills courses.