Rails 3:延迟加载与急切加载

在Rails 3中,它们是相同还是不同? 他们有什么不同?

o = Appointment.find(297) o.service o = Appointment.includes(:service).find(297) o.service 

我不确定,但看起来你在Appointment类中有belongs_to :serivce而且has_many :appointments Service类。 正确?

在这种情况下,你的两个例子之间没有任何区别。 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它实际上会获取所有约会1查询)。

在这种情况下,最好打电话:

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

因为那时Rails只会执行2个查询:一个用于获取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)