代码之家  ›  专栏  ›  技术社区  ›  99miles

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

  •  6
  • 99miles  · 技术社区  · 14 年前

    o = Appointment.find(297)
    o.service
    
    
    o = Appointment.includes(:service).find(297)
    o.service
    
    1 回复  |  直到 14 年前
        1
  •  7
  •   Community CDub    10 年前

    我不确定,但看起来你 belongs_to :serivce Appointment 类和 has_many :appointments Service 上课。对的?

    在这种情况下,你的两个例子没有任何区别。在这两种情况下,Rails将执行两个查询:

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