仅延迟预加载 Rails 中的某些关系列

问题描述 投票:0回答:1

我目前正在使用 ar_lazy_preload Gem,用于延迟预加载,但有时我只需要预加载这些关系的一些属性,我想知道是否有一种方法可以使用 select 只检索某些列,也许使用 Arel? (我不是很熟悉)

一个例子: 用户-人:1对1关系

User.lazy_preload(:person).all ,但从人员关系中只需要出生日期

我发现的最接近的问题是this它不适用于ar_lazy_preload

我希望延迟预加载,但使用一个查询,该查询使用选择来仅检索我需要的内容

users = User.lazy_preload(person: [:date_of_birth]).all
进行 1 次查询

Select * from users  
users.first.person.date_of_birth
再次查询

Select people.date_of_birth from people where people.user_id in ($ids from first query)

ruby-on-rails lazy-evaluation preload
1个回答
0
投票

你可以这样做:

 has_one :person_with_date_of_birth,
         -> { select(primary_key, :date_of_birth, :user_id) }, # Don't forget the foreign key field.  
         class_name: 'Person',
         foreign_key: :user_id,
         inverse_of: :user

现在你可以像这样使用它:

dates = User.all.lazy_preload(:person_with_date_of_birth).map do |user|
  # You have to modify your code changing `person` to `person_with_date_of_birth`. =/
  user.person_with_date_of_birth.date_of_birth
end

这并不优雅。但至少有效!这会产生以下 SQL:

SELECT "people"."id", 
       "people"."address_1", 
       "people"."user_id" FROM 
       "people" WHERE 
       "people"."user_id" IN (<user_ids>)
© www.soinside.com 2019 - 2024. All rights reserved.