views:

824

answers:

3

I'm following this tutorial (seems good) for Rails. After I run

ruby script/generate scaffold Post

then this link works in one of the erb files:

<%= link_to "My Blog", posts_path %>

WHY? I've looked for "posts_path" in the whole app and it's nowhere to be found. On the other hand, this

<%= link_to "My Blog", home_path %>

does not work, and it's also a Controller.

Where is the posts_path defined?

+8  A: 

posts_path is a named route you get for free from the route that was added by script/generate scaffold. See routes.rb you should see something like this:

map.resources :posts

See the API docs for information on what other named routes you get for free.

Also you can run rake routes and see what all your routes.rb is giving you.

If you want a home_path named route add a line like this to your routes.rb:

map.home '/home', :controller => "home", :action => "index"
Otto
Awesome! As you know, that worked. Still wondering why I need that huge line for "home" whereas I only need the map.resources for posts, but I imagine that it will all come clear soon...or after reading the API docs. Thanks again!
Yar
It's longer because it's departing from the RESTful routes conventions. You could do: map.resource :homeNote the non-plural resource. That would give you a home_path named route that went to that controller, but you would be stuck with /home. The other way, you can specify whatever you want.
Otto
Cool. I think your last line, corrected, is map.home '/home', :controller => "home", :action => "index"... because otherwise Rails wants to use HomeControllerController... THANKS again.
Yar
Yes, you're right. I'll correct the typo.
Otto
One important point, posts_path is a variable not a method.
jshen
+1  A: 

I believe that "posts_path" is created dynamically by Rails at runtime. Look at your routes.rb file - Home is probably not defined the same way as Posts. It has nothing to do with you controllers, it's dependent on the route definition.

Jason
+1  A: 

map.root :controller => "home" would be a shorter way of writing the path to your home directory. This will use / has the home, and not /home. If you still want to use /home (and home_path), map.home 'home', :controller => "home" will do the same thing.

There's a great guide written by Mike Gunderloy about everything there is to know about routing.

Ryan Bigg
Awesome, the tutorial already covered the map.root, but I still don't understand the LONG syntax for map.home and the short syntax for map.root, but perhaps if I read the guide you suggested I'll get there. Thanks for your answer!
Yar
map.root tells your application what to do when the route "/" (the index) is requested. map.home on the other hand defines a new route '/home' and then you must specify the route name (since it uses method_missing to generate it) and then the controller. map.root is so much better for that.
Ryan Bigg