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

99m*_*les 6 ruby-on-rails

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

o = Appointment.find(297)
o.service


o = Appointment.includes(:service).find(297)
o.service
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 7

我不知道,但它看起来像你belongs_to :serivceAppointmenthas_many :appointmentsService类.正确?

在这种情况下,您的两个示例之间不会有任何区别.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
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你打电话:

s = Service.find(123)
Run Code Online (Sandbox Code Playgroud)

然后做类似的事情:

s.appointments.find(1)
s.appointments.find(2)
Run Code Online (Sandbox Code Playgroud)

等在代码中的许多地方,那么会有许多数据库查询这些电话的数量(Rails 3中是非常聪明在这里,所以,如果你执行s.appointments.each它实际上取1个查询所有的约会).

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

s = Service.include(:appointments).find(123)
Run Code Online (Sandbox Code Playgroud)

因为那时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) 
Run Code Online (Sandbox Code Playgroud)