【发布时间】:2013-05-08 14:29:03
【问题描述】:
以下代码可以运行,但运行的 SQL 语句太多,我不喜欢;
User.includes([:profile,:roles]).select("id, email, created_at, confirmed_at, countries.name").find_in_batches do |users|
users.map{|u| # In here I access profile.country.name}
end
这样做的目的是获取用户信息以及一些个人资料信息并将其转换为 csv 格式。
在.map 内部,我正在调用profile.country.name,这很好,但 Rails 正在运行额外的 SQL 调用来查找名称,我想做的是在初始查找中捕获此信息。
我的问题是因为 country 链接到 profile 而不是 user 我不能将它添加到我的 .includes 因为它不将其视为可链接表。我可以做些什么来强制包含加入链接到profile 的表?
相关型号信息如下;
用户:
has_one :profile, dependent: :destroy
简介:
belongs_to :user
belongs_to :country
国家:
has_many :profiles
【问题讨论】:
标签: ruby-on-rails database activerecord