Rails 3: 惰性加载与急切加载

7
在Rails 3中,它们是相同的还是不同的?它们有什么区别?
o = Appointment.find(297)
o.service


o = Appointment.includes(:service).find(297)
o.service
1个回答

7
我不确定,但看起来你在Appointment类中有belongs_to :service,而在Service类中有has_many :appointments。是这样吗?
如果是这样的话,你的两个示例之间不会有任何区别。在这两种情况下,Rails都将执行2个查询:
Appointment Load (0.0ms)  SELECT "appointments".* FROM "appointments" WHERE ("appointments"."id" = 1) LIMIT 1
Service Load (0.0ms)  SELECT "services".* FROM "services" WHERE ("services"."id" = 1) LIMIT 1

如果你想要调用:

s = Service.find(123)

然后做一些像这样的事情:

s.appointments.find(1)
s.appointments.find(2)

如果代码中有许多这样的调用,则将有与这些调用数量相同的查询发送到数据库(Rails 3 在此方面非常智能,因此如果您执行s.appointments.each,它实际上会在一个查询中获取所有预约)。

在这种情况下,最好调用:

s = Service.include(:appointments).find(123)

因为这样Rails只会执行两个查询:一个是获取Service,另一个是获取所有的预约:

Service Load ( 0.0ms )  SELECT "services".* FROM "services" WHERE ("services"."i
d" = 123) LIMIT 1
Appointment Load ( 0.0ms )  SELECT "appointments".* FROM "appointments" WHERE ("
appointments".service_id = 123) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接