Ruby on rails 3.2 rails关联中的:include和:through选项之间有什么区别?
我不明白在哪种情况下我应该使用:include选项而不是:through选项 例如,我可以这样编写我的模型:Ruby on rails 3.2 rails关联中的:include和:through选项之间有什么区别?,ruby-on-rails-3.2,model-associations,Ruby On Rails 3.2,Model Associations,我不明白在哪种情况下我应该使用:include选项而不是:through选项 例如,我可以这样编写我的模型: Class Customer < ActiveRecord::Base has_many :orders, :include => :line_items end class Order < Active Record::Base belongs_to :customer has_many :line_items end class LineItem &
Class Customer < ActiveRecord::Base
has_many :orders, :include => :line_items
end
class Order < Active Record::Base
belongs_to :customer
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
Class Customer < ActiveRecord::Base
has_many :orders
has_many :lineitems, :through => :orders
end
class Order < Active Record::Base
belongs_to :customer
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
Class客户:行\u项目
结束
类顺序<活动记录::基
属于:客户
有很多:行项目
结束
类LineItem
或者我可以这样写:
Class Customer < ActiveRecord::Base
has_many :orders, :include => :line_items
end
class Order < Active Record::Base
belongs_to :customer
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
Class Customer < ActiveRecord::Base
has_many :orders
has_many :lineitems, :through => :orders
end
class Order < Active Record::Base
belongs_to :customer
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
Class客户:订单
结束
类顺序<活动记录::基
属于:客户
有很多:行项目
结束
类LineItem
多亏澄清了哪些练习与哪个选项相匹配。好的,我在彻底阅读了本手册后,才理解了其中的区别。A特别包括以下部分:关联加入模型和急切加载关联 事实上,它们与两个完全不同的概念有关: :通过选项可以在代码中构建快捷方式。 在我上面的(问题)示例中,我可以按照以下说明阅读行项目集合:
@customer.lineitems
而不是
@customer.orders.lineitems
注意事项是该属性是只读的
========
:include选项允许您在访问不同属性/方法时减少数据库中生成的查询数
使用:include in my association,以下代码在my DB中生成一个查询:
@customer.orders.lineitems
如果不使用:include,它将在my DB中生成两个查询
评论 如前所述,当模型不使用:include选项时,也可以在查询中直接使用该选项 在我上面的模型定义中,假设每个订单有10个行项目、每个客户有10个订单和10个客户,以下代码将生成101个查询,而不使用关联模型中的:include**选项: 全部1个,每个客户1个订单,每个订单1个行项目 (=1+(10个客户订单x 10个订单行项目) 此代码将生成12个查询,其中包含直接使用的查询: 1个用于收集订单id和参考订单,1个用于收集订单id和参考订单,1个用于收集10个订单中的每个订单的行项目:
Customer.includes(:orders).each do |customer|
customer.orders.each do |order|
puts "order number : " + order.number
order.lineitems.each do |lineitem|
puts "Item code : " + lineitem.code
end
end
end
orders集合将与customers集合同时检索(使用左外部联接sql查询)