Search code examples
ruby-on-railsruby-on-rails-3nested-resources

Dropping second model name in nested resource route


I'm using slugs for IDs, so wanting URLs like /songs/radiohead/karma-police instead of /artists/radiohead/songs/karma-police.

Slugs can be achieved with:

def to_param
  slug
end

But how is there any way to drop the model name - "songs" - from the standard RESTful URL?


Solution

  • You can override the path segment by passing the :path option to your resources call.

    resources :songs, path: "songs/:artist_id"
    

    this will generate these routes

          songs GET    /songs/:artist_id(.:format)          {:action=>"index", :controller=>"songs"}
                POST   /songs/:artist_id(.:format)          {:action=>"create", :controller=>"songs"}
       new_song GET    /songs/:artist_id/new(.:format)      {:action=>"new", :controller=>"songs"}
      edit_song GET    /songs/:artist_id/:id/edit(.:format) {:action=>"edit", :controller=>"songs"}
           song GET    /songs/:artist_id/:id(.:format)      {:action=>"show", :controller=>"songs"}
                PUT    /songs/:artist_id/:id(.:format)      {:action=>"update", :controller=>"songs"}
                DELETE /songs/:artist_id/:id(.:format)      {:action=>"destroy", :controller=>"songs"}