开发者

Rails 3: Lazy loading versus eager loading

开发者 https://www.devze.com 2023-01-20 18:15 出处:网络
In Rails 3, are these the same, or different? How do they differ? o = Appointment.find(297) o.service o = Appoin开发者_运维百科tment.includes(:service).find(297)

In Rails 3, are these the same, or different? How do they differ?

o = Appointment.find(297)
o.service


o = Appoin开发者_运维百科tment.includes(:service).find(297)
o.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?

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)

and then do something like:

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

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)

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) 
0

精彩评论

暂无评论...
验证码 换一张
取 消