下面的代码可以工作,但是运行的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中,这是很好的,但是rails正在运行一个额外的sql调用来查找名称,我想做的是在我的初始查找中捕获这个信息。
我的问题是,因为profile.country.name链接到country而不是profile,所以无法将其添加到我的user中,因为它不将其视为可链接的表。我可以做什么来强制includes加入链接到.includes的表吗?
相关型号信息如下:
用户:
has_one  :profile, dependent: :destroy

轮廓:
belongs_to :user
belongs_to :country

国家:
has_many :profiles

最佳答案

您应该可以通过将国家/地区嵌套在.includes调用中的配置文件下,将其包括在原始查询中:

User.includes( {:profile => [:country], :roles} )

10-06 05:15
查看更多