【问题标题】:How to generate the proper `url_for` a nested resource?如何生成正确的 `url_for` 嵌套资源?
【发布时间】:2012-06-06 00:25:48
【问题描述】:

我正在使用 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_associations, article_user_association, edit_article_user_association, ...

当我认为我使用时:

url_for([@article, @article_association])

然后我得到以下错误:

NoMethodError
undefined method `article_articles_user_association_path' for #<#<Class:0x000...>

但是,如果我这样声明路由器

# 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 方法相关的Official Documentation(特别是“命名路由的URL 生成”部分),但我找不到解决方案。当你想用self.primary_key 语句更改表的主键列时,也许有一种方法可以让 Rails 使用特定的命名路由器,就像它所做的那样......

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

  ...
end

【问题讨论】:

  • 我想知道是否存在与“关联”的命名冲突......它似乎只是在某处看到“model_associations”的记忆。
  • @DGM - 我不知道,但我认为这是很多人都会遇到的常见问题。
  • 不,我错过了命名空间的事情。

标签: ruby-on-rails ruby ruby-on-rails-3 routing named-routing


【解决方案1】:

您的 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 保留在命名空间中,否则不要这样做。

【讨论】:

  • 我知道,如果我删除命名空间,我会得到我正在寻找的路由助手,但原因是我有很多模型,为了让所有模型都保持简单“时尚”,我将它们定位/存储在 app/models 目录下的子目录中,因此我必须为它们命名。
猜你喜欢
  • 2023-04-08
  • 2016-09-17
  • 2018-04-03
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
相关资源
最近更新 更多