【问题标题】:How to avoid nested resources in Rails如何避免 Rails 中的嵌套资源
【发布时间】:2015-04-10 10:49:42
【问题描述】:

我目前的项目是制作一个日记应用程序,用户可以在其中登录并发布他们可以链接到 cmets 的文章。所以实现这个项目的非常自然的方式是这样的

resources :users do
  resources :articles do
    resources :comments
  end
end

Class User < ActiveRecord::Base
   has_many :articles
end

Class Article < ActiveRecord::Base
    belongs_to :user
    has_many :comments
end

Class Comment < ActiveRecord::Base
   belongs_to :article
end

但是,rails guide 表示资源的嵌套不得超过一层。有了这种关系,如何避免使用两级嵌套资源?

【问题讨论】:

  • rails 指南还告诉您如何避免这种情况。

标签: ruby-on-rails nested-resources


【解决方案1】:

查看 Rails 指南:http://guides.rubyonrails.org/routing.html#nested-resources 部分 2.7.2 浅嵌套。例如:

resources :articles do
  resources :comments, shallow: true
end

【讨论】:

    【解决方案2】:

    为避免这种情况,您需要使用Shallow Nesting。 rails 指南有完整的教程来说明如何做到这一点。在stackoverflow上也有很多与此相关的问题。以下是一些链接:

    http://guides.rubyonrails.org/routing.html#nested-resources

    When using shallow routes, different routes require different form_for arguments

    Rails 4 [Best practices] Nested resources and shallow: true

    https://railsforum.com/topic/1431-best-practices-nested-resources-and-shallow-true/

    如果您仍然遇到任何问题,那么您应该在 stackoverflow 上询问。

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 2019-08-11
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多