views:

36

answers:

1

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
A: 

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" = 1) LIMIT 1
Appointment Load (0.0ms)  SELECT "appointments".* FROM "appointments" WHERE ("
appointments".service_id = 1)
Matt