Rails 3:延迟加载与预先加载 [英] Rails 3: Lazy loading versus eager loading
问题描述
在 Rails 3 中,这些是相同的还是不同的?它们有何不同?
In Rails 3, are these the same, or different? How do they differ?
o = Appointment.find(297)
o.service
o = Appointment.includes(:service).find(297)
o.service
推荐答案
我不确定,但看起来您在 Appointment
类中有 belongs_to :serivce
和 has_many :appointments
Service
类.正确吗?
I'm not sure, but it looks like you have belongs_to :serivce
in the Appointment
class and has_many :appointments
the Service
class. Correct?
在那种情况下,您的 2 个示例之间不会有任何区别.在这两种情况下,Rails 都会执行 2 个查询:
In that case there won't be any difference between your 2 examples. Rails will execute 2 queries in both cases:
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
另一方面,如果你打电话给:
If, on the other hand, you were calling:
s = Service.find(123)
然后执行以下操作:
s.appointments.find(1)
s.appointments.find(2)
等等.在代码的许多地方,对数据库的查询将与这些调用的数量一样多(Rails 3 在这里非常聪明,所以如果你执行 s.appointments.each
它实际上会在 1 个查询中获取所有约会).
etc. in many places in the code, then there would be as many queries to the database as the number of these calls (Rails 3 is pretty smart here, so if you executed s.appointments.each
it would actually fetch all the appointments in 1 query).
在这种情况下,最好调用:
In that case it'd be better to call:
s = Service.include(:appointments).find(123)
因为 Rails 将只执行 2 个查询:一个获取 Service
,另一个获取所有约会:
because then Rails will execute only 2 queries: one to fetch the Service
and one to fetch all the appointments:
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)
这篇关于Rails 3:延迟加载与预先加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!