Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Activerecord 如何在Rails 4中加载父-子-父关联?_Activerecord_Ruby On Rails 4_Eager Loading - Fatal编程技术网

Activerecord 如何在Rails 4中加载父-子-父关联?

Activerecord 如何在Rails 4中加载父-子-父关联?,activerecord,ruby-on-rails-4,eager-loading,Activerecord,Ruby On Rails 4,Eager Loading,这是我关于StackOverflow的第一个问题:) 我正在构建一个Rails 4应用程序,很难找到从多个数据模型加载记录的好方法。我可以像内部联接一样硬编码SQL语句,但不知道是否有更好的方法。搜索了SO上的现有问题,但未找到匹配项 以下是我的模型: class Person < ActiveRecord::Base has_many :addresses end class Address < ActiveRecord::Base belongs_to :person

这是我关于StackOverflow的第一个问题:)

我正在构建一个Rails 4应用程序,很难找到从多个数据模型加载记录的好方法。我可以像内部联接一样硬编码SQL语句,但不知道是否有更好的方法。搜索了SO上的现有问题,但未找到匹配项

以下是我的模型:

class Person < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :person
  belongs_to :city
end

class City < ActiveRecord::Base
  has_many :addresses
end
class-Person
问题:给定一个个人Id,我应该如何加载与城市信息关联的地址

Address.includes(:persons,:cities).where(person_id: person.id)

这是许多方法之一。

谢谢你,巴巴。如果我只想选择列的子集呢?我尝试使用以下代码,但始终返回nil<代码>类地址
所属:person
所属:city
所属:city\u select\u columns,->{select(“column\u name”),:class\u name=>“city”
end
然后查询:
地址。包括(:person,:city\u select\u columns)。其中(person\u-id:person.id)
再次加入会更好,但既然我们已经在使用includes?那么它就出现了:
Address.includes(:persons,:cities)。选择(cities.column1,cities.column2,persons.column1,persons.column2…)。其中(person\u-id:person.id)