rails routing by id with reserved models
I want to have short URLs using an :id of one particular model instead of :model/:id.
I know how to make the :id work using a match
match ":id" => "artist#show", :as => :artist
That works fine, assuming of course i am careful with keeping somethings reserved, ie new/index开发者_开发知识库/edit etc.
But how can I then also keep other models working when no :id matches? IE /label or even /artist/new
I also would like to further do this with nesting so I also have... :artist_id/:album is there some easy way to deal with nested routes with custom paths?
Thanks
It all comes down to the precedence of each route. If you put all of your more-specific routes above your short-url route in routes.rb, they will be matched first. If nothing more specific matches, Rails will route it to artist#show.
You will probably want to take care to show a relevant error if no artist exists for the given ID, given that someone might not have been looking for an artist and would instead expect a generic 404 if there was an error.
Would it help to match only /\d+/
? You can guard route matching with such constraints. See: http://guides.rubyonrails.org/routing.html#segment-constraints
match ":id" => "artist#show", :as => :artist, :constraints => { :id => /\d+/ }
精彩评论