views:

186

answers:

1

I am attempting to create a custom route in rails and am not sure if I am going about it in the right way. Firstly I have a RESTful resource for stashes that redirects to mystash as the controller:

map.resources :stashes, :as => 'mystash'
site.com/mystash goes to :controller => 'stashes', :action => 'show'

Which is what I want. Now is where it gets somewhat confusing. I would like to be able to add conditional params to this route. Ultimately I would like to have a route that looks like this:

site.com/mystash/zoomout/new/quiz_on/

I have places this in routes:

map.connect 'mystash/:zoom/:nav_option/:quiz',
            :controller => 'stashes',
            :action => 'show'    
map.connect 'mystash/:zoom/:nav_option',
            :controller => 'stashes',
            :action => 'show'
map.connect 'mystash/:zoom',
            :controller => 'stashes',
            :action => 'show'
map.connect 'mystash',
            :controller => 'stashes',
            :action => 'show'

My routes have ended up looking like this in the browser: site.com//mystash/zoomin?nav_option=New&quiz=quizon

and this is what one of my links looks like:

<%= link_to "In", stash_path("zoomin", :nav_option => @nav_option, :quiz => @quiz) %>

Any help is appreciated, I am pretty new to custom routes!

+1  A: 

You should be giving these routes different names instead of the default, or you should be specifying your route with a hash and not a X_path call. For instance:

map.stash_zoom_nav_quiz 'mystash/:zoom/:nav_option/:quiz',
  :controller => 'stashes',
  :action => 'show'    
map.stash_zoom_nav 'mystash/:zoom/:nav_option',
  :controller => 'stashes',
  :action => 'show'

Keep in mind that when you declare a named route, the parameters in the path must be specified in the X_path call with no omissions, and not as a hash.

link_to('Foo', stash_zoom_nav_quiz_path(@zoom, @nav_option, @quiz))
link_to('Bar', stash_zoom_nav_path(@zoom, @nav_option))

The alternative is to not bother with named routes and let the routing engine figure it out on its own:

link_to('Foo', :controller => 'stashes', :action => 'show', :zoom => @zoom, :nav_option => @nav_option, :quiz => @quiz)

If you're uncertain what routes are defined, or how to call them, always inspect the output of "rake routes" very carefully. You can also write functional tests for routes with the assert_routing method.

tadman