1

以下代码有效,但运行了太多我喜欢的 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
4

1 回答 1

2

您应该能够通过将 country 嵌套在 .includes 调用中的 profile 下将其包含在原始查询中:

User.includes( {:profile => [:country], :roles} )
于 2013-05-08T14:40:34.783 回答