Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Rails Routes and Resources Routes to Create Actions Route for New Pages

new can have an id? how can new have an id?

why would the rails app match the new even though it's not an object, specifically, what is rails doing and looking for when it looks for an id in a url parameter?

why would /pages/new --> /pages/:id

2 Answers

An important thing to remember is that Rails processes the routes.rb file in order of the route declarations. Once a match is found, Rails stops looking for other matches and processes the route with the matched controller action.

In the initial example in the video, the /pages/new url was matching the /pages/:id route because /pages/:id will match any URL that has /pages/ followed by a string.

Typically, we'd want this string to be a number corresponding to the id in the database for the pages model, but technically the routing in rails will match any string

Based on this, we need to put the route for /pages/new before the /pages/:id route in the file so it gets triggered first.

yvesramos
yvesramos
12,816 Points

I still have some doubt with this. Can someone explain what his both do?

get '/pages/:id' to: 'pages#show', as: 'page' and get '/pages/new', to: 'pages#new'

Thanks