I have a group model which has_many article model. And I want to use the following url pattern “{group_id}/{article_id}”.
so I wrote these route codes:
resource :groups do
resource :articles
end
match ':group_id/:id(.:format)', :to => 'articles#show', :as => :article
match ':id', :to => 'groups#show', :as => :group
But rails fail to generate correct url for group records and article records. How can I replace the automatic generated article_path and group_path to match my routes?
You’re running into problems because you aren’t watching out for pluralization. When you define a singular
resourceroute, Rails doesn’t treat it as a collection where you would refer to each member with anid. You instead want a pluralresourcesfor both groups and articles:Generates the following routes:
If you want to leave off the
groupsandarticlessegments you can pass:path => ''to each of theresourcesdefinitions, but you are going to have to tread carefully because any request to http://example.com/1/2 will map to an article under groups and be uninformative to end users and bots alike.