如何生成适当的`url_for`嵌套资源?

我正在使用Ruby on Rails 3.2.2,我想为嵌套资源生成一个正确的url_for URL。 也就是说,我有:

 # config/routes.rb resources :articles do resources :user_associations end # app/models/article.rb class Article < ActiveRecord::Base ... end # app/models/articles/user_association.rb class Articles::UserAssociation < ActiveRecord::Base ... end 

注意 :生成的命名路由类似于article_user_associationsarticle_user_associationedit_article_user_association ,…

在我看来,我使用:

 url_for([@article, @article_association]) 

然后我收到以下错误:

 NoMethodError undefined method `article_articles_user_association_path' for #<# 

但是,如果我以这种方式说明路由器

 # config/routes.rb resources :articles do resources :user_associations, :as => :articles_user_associations end 

url_for方法按预期工作,例如,它生成URL /articles/1/user_associations/1

注意 :在这种情况下,生成的命名路由类似于article_articles_user_associationsarticle_articles_user_associationedit_article_articles_user_association ,…

但是,我认为路由器在后者/工作案例中构建/命名的方式并不“好”。 那么, 是否有可能以某种方式通过生成像article_user_association这样的命名路由(而不是像article_articles_user_association )来使url_for方法工作?


我阅读了与ActionDispatch::Routing::UrlFor方法相关的官方文档 (特别是“命名路由的URL生成”部分),但我找不到解决方案。 也许有一种方法可以“说”Rails使用特定的命名路由器,就像它想要用self.primary_key语句更改表的主键列self.primary_key

 # app/models/articles/user_association.rb class Articles::UserAssociation < ActiveRecord::Base # self.primary_key = 'a_column_name' self.named_router = 'user_association' ... end 

您的UserAssociation模型位于Articles命名空间中,该命名空间包含在命名路由中:

 # app/models/articles/user_association.rb class Articles::UserAssociation < ActiveRecord::Base ... end # route => articles_user_association # nested route => article_articles_user_association 

如果删除命名空间,您将获得您正在寻找的路由助手:

 # app/models/articles/user_association.rb class UserAssociation < ActiveRecord::Base ... end # route => user_association # nested route => article_user_association 

除非您有充分的理由将UserAssociation保留在命名空间中,否则不要这样做。