我有公司表和城市表;公司属于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
获取非常重要。
答案 0 :(得分:2)
在includes
中尝试Company.includes(:city).first.city.title
。