我使用 slugs 作为 ID,所以想要 /songs/radiohead/karma-police 之类的 URL,而不是 /artists/radiohead/songs/karma-police。
蛞蝓可以通过以下方式实现:
def to_param
slug
end
但是如何从标准 RESTful URL 中删除模型名称 - “歌曲”?
我使用 slugs 作为 ID,所以想要 /songs/radiohead/karma-police 之类的 URL,而不是 /artists/radiohead/songs/karma-police。
蛞蝓可以通过以下方式实现:
def to_param
slug
end
但是如何从标准 RESTful URL 中删除模型名称 - “歌曲”?
您可以通过将:path
选项传递给您的resources
调用来覆盖路径段。
resources :songs, path: "songs/:artist_id"
这将生成这些路线
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"}
Put this in your routes.rb
and it should work.
match 'artists/:artist_id/:id' => 'songs#show', :as => 'artist_song'
Make sure if you do the :as
that the other routes don't take precedence over this one.
Then check out this Routing match
reference