使用属性访问器嵌套的eager加载

时间:2013-08-08 20:58:03

标签: ruby-on-rails associations lazy-loading rails-models

我的模型设置如下:

class Country < ActiveRecord::Base
   has_many :manufacturers
end

class Manufacturer < ActiveRecord::Base
   belongs_to :country
   has_many :cars
end

class Cars < ActiveRecord::Base
   belongs_to :manufactuer
   has_many :comfort_levels

   attr_accessor :attr_accessor_1, :attr_accessor_2
end

class ComfortLevel < ActiveRecord::Base
   belongs_to :car
end

这就是我急切地为一个国家/地区加载manufacturers cars(包括汽车的attr访问者)的方式:

data = current_country.manufacturers.to_json :include => {:cars => {:methods => [:attr_accessor_1, :attr_accessor_1]}}

在上述调用中,还会急切加载comfort levels cars的语法是什么?

我尝试过各种各样的东西,但到目前为止还没有运气。

非常感谢这方面的任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

你试过这个吗?

data = current_country.manufacturers.to_json :include => {:cars => {:methods => [:attr_accessor_1, :attr_accessor_1], :comfort_levels => {}}}

答案 1 :(得分:0)

我终于能够使用以下方式加载所有内容:

data = current_country.manufacturers.to_json :include => [{:cars => {:methods => [:attr_accessor_1, :attr_accessor_1]}}, :comfort_levels]

上述调用未在comfort level条记录中嵌套car条记录,但是,以下内容确实如此:

data = current_country.manufacturers.to_json :include => {:cars => {:methods => [:attr_accessor_1, :attr_accessor_1, :comfort_levels]}}

这个link帮助我清楚了解急切加载语法的一些概念。