当连接表时,当从连接表访问字段时,rails仍会提出额外的请求

时间:2014-12-17 10:23:27

标签: ruby-on-rails ruby

我有公司表和城市表;公司属于city。

我的数据库架构的一部分是:

  create_table "companies", force: true do |t|
    t.string   "title",      default: "", null: false
    t.string   "address",    default: "", null: false
    t.integer  "city_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "cities", force: true do |t|
    t.string   "title",      default: "", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "test"
  end

Company模型的一部分:

class Company < ActiveRecord::Base
  belongs_to    :city,   :inverse_of => :companies
  # ....
end

City模型的一部分:

class City < ActiveRecord::Base
  has_many      :companies, :inverse_of => :city
  # ....
end

当我获取公司,然后获得其城市名称时,显然Rails会提出额外的请求以获取城市标题:

$ rails console
2.1.5 :001 > Company.first.city.title
  Company Load (0.2ms)  SELECT  "companies".* FROM "companies"   ORDER BY "companies"."id" ASC LIMIT 1
  City Load (0.3ms)  SELECT  "cities".* FROM "cities"  WHERE "cities"."id" = ? LIMIT 1  [["id", 2]]
 => "My city 1"

我很确定通过加入cities表可以避免这种情况。但我错了:

2.1.5 :002 > Company.joins(:city).first.city.title
  Company Load (0.3ms)  SELECT  "companies".* FROM "companies" INNER JOIN "cities" ON "cities"."id" = "companies"."city_id"  ORDER BY "companies"."id" ASC LIMIT 1
  City Load (0.1ms)  SELECT  "cities".* FROM "cities"  WHERE "cities"."id" = ? LIMIT 1      [["id", 2]]
 => "My city 1" 

因此,cities表已加入,但Rails仍会向cities执行其他请求。

为什么会这样,以及如何避免对cities表的其他请求?

当我只有一条记录时(例如上面的示例),它并没有太大的伤害,但如果我想得到Company.joins(:city).all,然后获得每个公司的城市,那么每个公司的额外开销从cities获取非常重要。

1 个答案:

答案 0 :(得分:2)

includes中尝试Company.includes(:city).first.city.title