【问题标题】:ActiveRecord: Has_many inside another has_many - with rails3ActiveRecord:另一个 has_many 中的 Has_many - 使用 rails3
【发布时间】:2012-12-20 18:28:24
【问题描述】:

所以我正在建立一个由页面和应用程序以及应用程序内容组成的系统。其中一个页面 has_many :app_instances 和 app_instances has_many :app_contents。

我有模型: 页面、应用、app_instance、app_content

在我的模型中:

class Page < ActiveRecord::Base
  has_many :app_instances
end

class App < ActiveRecord::Base
  belongs_to :page
end

class AppInstance < ActiveRecord::Base
  belongs_to :page
  belongs_to :app
  has_many :app_contents
end

class AppContent < ActiveRecord::Base
  belongs_to :app_instance
  belongs_to :app
end

我想要一个对象,其中所有内容都在应用程序实例下的单个内容下......但是有没有办法做到这一点?

我在我的一个控制器中设置了这个:

@page = Page.includes(:app_instances).find(params[:id])

我可以成功调试@page.app_instances,但我一说@page.app_instances.app_contents 就会出错。我猜这只是因为我缺少包含中的包含,但不确定我是如何写的,或者即使这是“好的做法”

我知道我可能会这样做:

has_many :app_contents, :through => :app_instances

但 id 宁愿让对象与保存内容的实例一起组织(这很有意义,对吗?)...所以我可以遍历所有实例,并打印出实例的内容

我的数据库架构有意义吗?还是我走错路了

乔尔

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord has-many


    【解决方案1】:

    您可以包含嵌套使用:

    Page.includes(:app_instances=>[:app_contents])
    

    但您收到错误的主要原因是,在@page.app_instances.app_contents page.app_instances 没有任何app_contents。您将寻找 app_contents 的联合 app_instances@page

    所以可以通过:

    @page.app_instances.app_contents.each{|ai| (list || =[]) << ai.app_contents}
    list.flatten!
    

    在您的模型中定义page has many app_contents through app_instances 关系。

    第一种情况会为 each app_instances 运行查询,但是使用 includes 正如我之前提到的那样,这将导致单个查询。第二种情况会导致单个连接查询加入 app_contents、app_instances 表

    【讨论】:

    • 是的..它最好地定义了页面和app_contents的关系,并且查询实际上得到了更好的优化..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多