1

每当我尝试调用它时:

  @ships = Ship.find(:all,
                    :conditions => {:sold => params[:sold]},
                    :order => "ship.id desc")

从这个模型:

class Ship < ActiveRecord::Base
    self.table_name = 'ship'

    self.inheritance_column = :ruby_type
    belongs_to :brand, :class_name => 'Brand', :foreign_key => :brand    
    belongs_to :fuel, :class_name => 'Fuel', :foreign_key => :fuel    
    has_many :ship_pictures, :class_name => 'ShipPicture'
    has_many :reservations, :class_name => 'Reservation'    
end

我最终得到了这些查询:

  Ship Load (0.0ms)  SELECT "ship".* FROM "ship" WHERE "ship"."sold" = 'false' ORDER BY ship.id desc
  Brand Load (0.0ms)  SELECT "brand".* FROM "brand" WHERE "brand"."name" = 'Percedes' LIMIT 1
  Fuel Load (0.0ms)  SELECT "fuel".* FROM "fuel" WHERE "fuel"."name" = 'Air' LIMIT 1
  ShipPicture Load (0.0ms)  SELECT "ship_picture".* FROM "ship_picture" WHERE "ship_picture"."ship_id" = 2
  Brand Load (1.0ms)  SELECT "brand".* FROM "brand" WHERE "brand"."name" = 'Volksship' LIMIT 1
  Fuel Load (1.0ms)  SELECT "fuel".* FROM "fuel" WHERE "fuel"."name" = 'Nuclear Reactor' LIMIT 1
  ShipPicture Load (0.0ms)  SELECT "ship_picture".* FROM "ship_picture" WHERE "ship_picture"."ship_id" = 1

为什么会这样?我没有打电话 :include 或类似的东西?我想加入 ship_pictures 并且只获得该加入的第一个结果。

第二件事:什么被认为更好:象征方式还是方法方式?

4

1 回答 1

3

这似乎不是在这里玩的延迟加载。如果使用延迟加载,我希望只看到三个查询BrandFuel并且ShipPictureSQL 如下:

WHERE "ship_picture"."ship_id" IN [1,2]

您的Ship模型中是否还有其他代码调用了这些关联?

如果您上面的查找器来自控制器,您可能正在调用ship.fuelship.brand或者ship.ship_pictures在您的视图中的某个地方。这是 N+1 查询的常见原因。如果它不是来自控制器,那么它很可能是在查询结果上运行的其他代码。

于 2012-10-15T20:36:20.670 回答