想要获得在特定帐户和注册时注册的用户各自的奥特莱斯。
用户&插座型号没有任何关联。
Outlet has_and_belongs_to_many accounts&反之亦然
用户包含字段outlet_code,该字段在outlet表中是唯一的
@account = Account.find(2546)
@outlet_ids = @ account.outlets.map(&:id)#-----它返回这样的数组[1,2,3 .... 1032457],这是动态的
我使用了这个效率不高的查询=> @users = User.where(:outlet_code => @outlet_ids)
答案 0 :(得分:2)
我认为您需要的是批量延迟加载和处理。
您可以获得的最有效率(假设您以任何方式处理集合)是使用find_each
:
@users = User.where(id: [1,2,3....450000]).find_each.lazy
会返回lazy枚举器的实例:
#<Enumerator::Lazy: ...>
现在你可以使用它并迭代 - @users
将根据需要从数据库加载(懒惰)。
答案 1 :(得分:0)
将find_each用于批量大小: -
@users = User.where(:id => [1,2,3....450000]).find_each(batch_size: 50 or no. of records you want to get in batch)
我将返回以下记录: -
#<Enumerator: #<ActiveRecord::Relation [...]>
find_each with block: -
@users = User.where(:id => [1,2,3....450000]).find_each(batch_size: 50 ) do |user|
# your code here
end
# User Load (0.7ms) SELECT "users".* FROM "users"
# ORDER BY "users"."id" ASC LIMIT 50
# User Load (0.6ms) SELECT "users".* FROM "users"
# WHERE ("users"."id" > 50) ORDER BY "users"."id" ASC LIMIT 50
# USer Load (0.3ms) SELECT "users".* FROM "users"
# WHERE ("users"."id" > 100) ORDER BY "users"."id" ASC LIMIT 50