父对象渴望加载嵌套关联Rails

时间:2015-05-29 17:53:46

标签: ruby-on-rails-4 activerecord has-many-through eager-loading

在Rails 4中,我有以下型号

class Parent < ActiveRecord::Base
 has_many :sons
 has_many :grand_sons, through: sons

 scope :load_tree, (id) -> {Parent.includes(sons: [:grand_sons]).find(id)}
end

class Son < ActiveRecord::Base
  belongs_to :parent
  has_many :grand_sons
end

class GrandSon < ActiveRecord::Base
  belongs_to :son
end

使用load_tree我想获得一个像这样的对象:

{ 
  id: 1, 
  sons: [
          { 
            id: 1, 
            parent_id: 1, 
            grand_sons:[ { id: 1, son_id: 1, } , ...]
          }, ...
        ]
 }

但在完成tree = Parent.load_tree(1)之后我得到tree # <Parent id=1> tree.sons #[<Son id=1>, <Son id =2>]所以我似乎无法急切加载所有对象,有什么建议吗?

1 个答案:

答案 0 :(得分:2)

尝试

Parent.includes(:sons, {:sons => :grand_sons}).find(id)

我的理解是,您必须明确指定嵌套关联的关系。