Rails Routes for Rookies

You can write to give you just the index and show routes OR you can put resources :raccoons, except: [:index], which you guessed it, gives you everything but the index route.

Thanks rails!resources :raccoons, only: [:index, :show] #this will give you just the index and show routesresources :raccoons, except: [:index] #this will give you all routes except indexRails Routes is your friendYou can always see what routes you have defined, along with their helper methods when you run rails routes in your terminal.

This really helped me understand what was happening when I was creating links in my web app, and realizing what path I needed to send it to.

Each of these has a corresponding URL helper, so if you wanted to see a list of your raccoons you can see the URL would be localhost:3000/raccoons.

Likewise, if you wanted to see a specific raccoon you would type in, for example, localhost:3000/raccoons/1.

Renaming URLsWhat if you have a sessions controller that logs in your user, but you don’t want the URL to be localhost:3000/sessions/new but instead want it to be localhost:3000/login?.Well, we can do that!.Below you can see that if you use the as: function, it will turn our path into /loginChanging sessions/new into /loginIf we run rails routes, we can see that routes added a login path for us.

Rails routes shows us what our path looks like nowNested RoutesWhat are they?.For example, we wanted to add comments to our raccoon pages.

With nested routes, this will allow us to find the comment for a specific raccoon inside our raccoon show action.

So let’s add comments under the raccoons resources in our route.

rb file.

Let’s run rails routes and see what routes we have now!rails routes for our nested routesYou can see that we now have comments under our raccoon routes.

By having these URLs, we now have access to two params necessary to find the requested object, raccoon_id and id(which is the comment id).

Of course, nested routes can get a little out of hand if you have too many.

It’s best to try and keep your nested routes from going deeper than one level.

Hopefully, this has cleared up some confusion on routes, below are a few pages that I read through to try and get a better understanding.

Check them out.

Routes cheatsheetRails Routing from the Outside In — Ruby on Rails Guides4 things i learned toying around with nested resources in Rails.

. More details

Leave a Reply