DEV Community


Posted on

Ruby on Rails & Routes

As a developer one of the things I always look in my applications is simplicity. Simplicity in my code and a good user-friendly experience for my users. Our routes and the way we set them up would make a big difference in the overall performance of our app.

Rails is a really beautiful and magical thing, and that apply to our routes too.The Rails router recognizes the URLs and sends them to the action of a controller. You can also generate routes and URLs, avoiding the need for code strings in your views (yes, this's not Sinatra anymore). In general, "routing" is how URLs are "handled" by your application. In the case of Rails, it's generally what controller and what action from that controller will handle a particular inbound URL. In Rails applications, the paths are located in the file config/routes.rb.

A great way to set your routes is using resources :users. This would automatically create seven routes (all of them connected to our UserController actions. The seven routes are the following:

Alt Text

Routes can be declared available only to specific members (not collections) using the method resource instead of the resources in routes.rb. With resource, an index path is not created by default, but only when one like this is explicitly requested:

Alt Text

Another really useful way to organize our routes is by using nested routes. The way I use to understand nested routes is thinking about it like a really organized way to create routes based on your ActiveRecord Associations. For example, you could guess a figure has many comments just to looking a route like this --> "/figures/2/comments/4".

Alt Text

There's two really important rules I just learned using nested routes this past couple of weeks:

  1. If we didn't specifically restrict the routes, Rails would generate all the typical routes for the nested resource as well. Be really specific and have a clear idea of how your routes should look like.

  2. As a general rule, never generate any of the member routes when nesting. Member routes should only belong to top-level resources. There's nothing wrong with defining the same resource at two levels.

Routes can be confusing at first, but if you have a clear understanding of how to use RESTful routes and how to set up your associations from the beginning this task would be one of the most useful because your routes are that first real interaction with the logic behind your application.

Thank you for reading! :)

Discussion (0)