在嵌套资源路由中删除第二个模型名称

时间:2012-01-07 22:05:09

标签: ruby-on-rails ruby-on-rails-3 nested-resources

我使用slugs作为ID,所以想要/ songs / radiohead / karma-police等网站而不是/ artists / radiohead / songs / karma-police。

可以通过以下方式实现S ::

def to_param
  slug
end

但是有什么方法可以放弃模型名称 - "歌曲" - 来自标准的RESTful URL?

2 个答案:

答案 0 :(得分:1)

您可以通过将: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"}

答案 1 :(得分:0)

将它放在routes.rb中,它应该有效。

match 'artists/:artist_id/:id' => 'songs#show', :as => 'artist_song'

确保您执行的:as其他路线不优先于此路线。

然后查看此Routing match reference