Easy Rails Routing Configuration

I am creating a storyy Ruby on Rails application. Each story has several pages.

How to configure route.rb so that I have the following URLs:

http://mysite.com/[story id]/[page id] 

how

 http://mysite.com/29/46 

I am currently using this setting:

 http://mysite.com/stories/29/pages/46 

Using:

 ActionController::Routing::Routes.draw do |map| map.resources :stories, :has_many => :pages map.resources :pages map.root :controller => "stories", :action => "index" map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end 

Thanks in advance. I'm new to Rails and routing seems a bit trickier for me right now.

+4
source share
3 answers

Here is a good resource.

 map.connect 'stories/:story_id/:page_num', :controller => "stories", :action => "index", :page_id => nil 

In your controller:

 def index story = Story.find(params[:story_id]) @page = story.pages[params[:page_num]] end 

UPDATE: Just noticed that you donโ€™t need โ€œstoriesโ€. Not sure if you drop this from the map.connect file, try it.

 map.connect '/:story_id/:page_num', ... 
+6
source

Given the route

 map.connect '/:story_id/:id', :controller => 'pages', :action => 'show' 

You can do it in your controller

 def show @story = Story.find(:story_id) @page = @story.pages.find(:id) end 

Now you can get the page using the story id.

PS: map.connect ':story_id/:id' should work.

+1
source

I'm not sure why no one suggested just using a named route. Sort of

 map.story '/:story_id/:page_id', :controller => 'stories', :action => 'show' 

then you can just call it with

 story_path(story.id,params[:page}) 

or something similar.

+1
source

All Articles