Ruby on Rails Web App pt 2 - Routing

By Nick Rodriguez

Rails guide on routing.

To save development time, it's extremely helpful to think through what routes we'll want to implement ahead of time. Rather than adding all possible routes, we should practice intentionality by determining exactly what resources we'll need, and which of those need to be user-facing. In this case, we don't want users to see an index of all users, nor do we want to be able to delete users, so we'll deliberately omit those routes. Tables, unsurprisingly, come in handy here:

rails_web_app_routes_other.PNG

Now that we know which routes we'll need, we can start building our routes file.

rails_web_app_routes_sessions.png
/config/routes.rb

Note that since we want the user to login at /login and not /sessions/new, we manually define that route instead of adding the new resource route. Additionally, we add a custom callback route that will receive data from our Omniauth integration, allowing users to login/register with Twitter, Facebook, and Google. Similarly, we can build out our User, Review, and View routes, manually defining our users#new route, and nesting our reviews#index and views#index routes under users.

rails_web_app_routes_user.png
User routes

We only need to nest the index actions for Review and Views, since the respective objects should be scoped to those that belong to a specific User. That is, we don't want an index of all reviews to show up on a User's profile, only those that User has written. Further, creating, editing, updating, and destroying Reviews and Views doesn't require any context related to the User that owns those objects; there's no need for those actions to be performed in that context.

We can build a similar table to plan out our Media routes.

rails_web_app_routes_media.PNG

Important things to note here: 

  • Only need four actions.
  • Index for Season and Episode aren't needed.
  • New for Season and Episode need to be nested (need context).

That leads us to build the following routes:

rails_web_app_routes_media.png
Media routes

Now we just need to account for these actions in each respective controller.

View the source on GitHub.


  Ruby on Rails Web App pt 1 - Models & Migration|Creating a JSON API in Rails