在Rails 3中,它们是相同的还是不同的?它们有什么区别?
o = Appointment.find(297)
o.service
o = Appointment.includes(:service).find(297)
o.service
o = Appointment.find(297)
o.service
o = Appointment.includes(:service).find(297)
o.service
Appointment
类中有belongs_to :service
,而在Service
类中有has_many :appointments
。是这样吗?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)