我有一个has_many
文章模型的群组模型。我想使用以下网址格式“{group_id} / {article_id}”。
所以我写了这些路线代码:
resource :groups do
resource :articles
end
match ':group_id/:id(.:format)', :to => 'articles#show', :as => :article
match ':id', :to => 'groups#show', :as => :group
但是rails无法为组记录和文章记录生成正确的URL。如何替换自动生成的article_path
和group_path
以匹配我的路线?
答案 0 :(得分:1)
你遇到问题因为你没有注意多元化。当您定义单个resource
路由时,Rails不会将其视为一个集合,您可以使用id
来引用每个成员。相反,您希望对组和文章都使用复数resources
:
resources :groups do
resources :articles
end
生成以下路线:
group_articles GET /groups/:group_id/articles(.:format) {:action=>"index", :controller=>"articles"}
POST /groups/:group_id/articles(.:format) {:action=>"create", :controller=>"articles"}
new_group_article GET /groups/:group_id/articles/new(.:format) {:action=>"new", :controller=>"articles"}
edit_group_article GET /groups/:group_id/articles/:id/edit(.:format) {:action=>"edit", :controller=>"articles"}
group_article GET /groups/:group_id/articles/:id(.:format) {:action=>"show", :controller=>"articles"}
PUT /groups/:group_id/articles/:id(.:format) {:action=>"update", :controller=>"articles"}
DELETE /groups/:group_id/articles/:id(.:format) {:action=>"destroy", :controller=>"articles"}
groups GET /groups(.:format) {:action=>"index", :controller=>"groups"}
POST /groups(.:format) {:action=>"create", :controller=>"groups"}
new_group GET /groups/new(.:format) {:action=>"new", :controller=>"groups"}
edit_group GET /groups/:id/edit(.:format) {:action=>"edit", :controller=>"groups"}
group GET /groups/:id(.:format) {:action=>"show", :controller=>"groups"}
PUT /groups/:id(.:format) {:action=>"update", :controller=>"groups"}
DELETE /groups/:id(.:format) {:action=>"destroy", :controller=>"groups"}
如果您想离开groups
和articles
段,可以将:path => ''
传递给每个resources
定义,但是您必须谨慎行事因为对http://example.com/1/2的任何请求都会映射到群组下的文章,并且无法向最终用户和机器人提供信息。