问题描述
我有公司表和城市表;公司属于城市.
I have companies table and cities table; company belongs to city.
我的数据库架构的一部分是:
Part of my db schema is:
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
公司
模型的一部分:
class Company < ActiveRecord::Base
belongs_to :city, :inverse_of => :companies
# ....
end
City
模型的一部分:
class City < ActiveRecord::Base
has_many :companies, :inverse_of => :city
# ....
end
当我获取公司,然后获取它的城市名称时,很明显 Rails 会发出额外的请求来获取城市名称:
When I fetch company, and then get its city title, it's obvious that Rails would make an additional request to fetch the city title:
$ 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
表来避免这种情况.但我错了:
And I was pretty sure I can avoid this by joining cities
table. But I was wrong:
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
执行额外的请求.
So, cities
table was joined, but Rails anyway performs additional requests to cities
.
这是为什么,以及如何避免对 cities
表的额外请求?
Why is this, and how to avoid additional requests to cities
table?
当我只有一条记录时(如上例所示)不会有太大影响,但是如果我想获得 Company.joins(:city).all
,然后获得城市对于每个公司,每次从 cities
获取的额外开销是非常重要的.
It doesn't hurt much when I have just one record (as in the example above), but if I want to get Company.joins(:city).all
, and then get city of each company, then additional overhead for each fetch from cities
is very significant.
推荐答案
像 Company.includes(:city).first.city.title
一样尝试 includes
.
这篇关于连接表时,rails 无论如何都会在访问连接表中的字段时发出额外请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!