Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

named routes not recognizing parameters

#5948

i'm trying to generate a show url for a model for which the route defined is:

match '/model_x/:slug', :to => 'model_xs#show', :as => 'model_x', :via => 'get' resources :model_x, :except => ["show"]

rake routes shows me:

                model_x GET    /model_xs/:slug(.:format)                      {:controller=>"model_xs", :action=>"show"}
                model_xs GET    /model_xs(.:format)                           {:action=>"index", :controller=>"model_xs"}
                model_xs POST   /model_xs(.:format)                           {:action=>"create", :controller=>"model_xs"}
             new_model_x GET    /model_xs/new(.:format)                       {:action=>"new", :controller=>"model_xs"}
            edit_model_x GET    /model_xs/:id/edit(.:format)                  {:action=>"edit", :controller=>"model_xs"}
                 model_x PUT    /model_xs/:id(.:format)                       {:action=>"update", :controller=>"model_xs"}
                 model_x DELETE /model_xs/:id(.:format)                       {:action=>"destroy", :controller=>"model_xs"}

expected:

model_x_path(ModelX.find_by_slug('slug-for-model-x-1')) should give me '/model_xs/slug-for-model-x-1'

actual:

model_x_path(ModelX.find_by_slug('slug-for-model-x-1')) gives me '/model_xs/1'

this route is invalid as i have added :except => ["show"] to the resource route and defined routing to action show only by slug in the url.

even, model_x_path(:slug => 'slug-for-model-x-1') doesn't work.

Reported by vinay · November 10th, 2010 @ 11:03 PM

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Andrew White
    Andrew White
    • State changed from new to invalid
    • Importance changed from to Low

    Firstly the reason that model_x_path(@instance) gives '/model_xs/1' is that the to_param method returns the model id by default. Override to_param to return the slug if that's what you want.

    The second error is because multiple routes share the url helper model_x_path and the last one declared has precedence. In this case it's the destroy action so it's looking for an :id parameter rather than a :slug parameter. Moving the match route after the resources call makes it work but model_x_path(:id => @model.id) then doesn't work.

    If you stick to positional arguments then it will work - model_x_path(@model.id) and model_x_path(@model.slug). Also using url_for will select the correct route. However it's easier to remove the match route and use the default show route generated by the resources call - the params in the url are not tied to the model in anyway.

    November 11th, 2010 @ 10:37 AM