views:

71

answers:

2

I'm currently following the Shovell tutorial in the Simply Rails 2 book. On page 168, it mentions URL Helpers for the Story Resource:

stories_path                 /stories
new_story_path               /stories/new
story_path(@story)           /stories/1
edit_story_path(@story)      /stories/1/edit

The above is then used in the controller:

def create
  @story = Story.new(params[:story])
  @story.save
  redirect_to stories_path
end

My routes.rb:

ActionController::Routing::Routes.draw do |map|
  map.resources :stories
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

It looks like stories_path is the url name to /stories. Is that explicitly defined somewhere within my app, I can't seem to grep for that keyword. If not, is there a way that I can check the mapping above from the Rails console or somewhere else? In Django, url names are usually explicitly defined in urls.py, I just can't figure out how the above is being generated. Any documentation and pointers will help.

+1  A: 

To get a list of the mapped routes:

rake routes

What map.resources :stories is doing is mapping your RESTful actions (index, show, edit etc.) from the stories_controller.rb to named routes that you can then use for simplicity.

routes.rb includes helpful tips on defining custom routes and it may be worth spending a little bit of time looking at resources in the API to get a better understanding: http://api.rubyonrails.org/classes/ActionController/Resources.html#M000522

Mark Connell
A: 

I think checking out the Rails Guides on Routing will help you a lot to understand what's going on

In short, by using the

map.resources :stories

the Router will automatically generate some useful (and RESTful) routes. Their path will take the model name (remember in Rails there is the Convention over Configuration motto), and, by default, will generate routes for all the REST actions.

This routes are available through your controller, views, etc.

If you want to check out which routes are generated from your mappings, you can use the "rake routes" command.

Now, given that, you can also write explicit URLs on your routes.rb file for actions or events that don't quite comply with the REST paradigm.

For that, you can use

map.connect "/some_kind_of_address", :controller => :pages, :action => "something_else"

Or

map.home "/home", :controller => :pages, :action => "home"

The last one will gave you both home_path and home_url routes you can use in your code.

Yaraher