首页 > 解决方案 > ActiveRecord、pgsql:通过多个索引查询多条记录

问题描述

在我的Users表中,用户由对account_id和的唯一多重索引定义location_id
当我收到获取特定帐户/位置对的数据的请求时,我可以轻松检索这一对的数据:

account_location_hash = { account_id: 2, location_id: 3 }
user = User.find_by(account_location_hash)

但是,当我需要找到多个用户,拥有一组哈希(数百对)时,没有简单的方法来获取我需要的实体,尽管我已经获得了这些实体的预期索引列表。
我尝试使用:

pairs_array = [{ account_id: 2, location_id: 3 },{ account_id: 1, location_id: 4 }]
user = User.where(pairs_array)

但这不起作用。

我可以找到更复杂的解决方案,例如构建 AND 和 OR 的查询,或者创建我得到的对的临时表并加入表,但没有一个感觉是正确的。
我错过了更简单的方法吗?

标签: ruby-on-railspostgresqlactiverecord

解决方案


我认为最简单的解决方案是:

pairs_array = [{ account_id: 2, location_id: 3 },{ account_id: 1, location_id: 4 }]

account_ids = []
location_ids = []
pairs_array.each do |h|
  account_ids << h[:account_id]
  location_ids << h[:location_id]
end

User.where('account_id IN (?) AND location_id IN (?)', account_ids, location_ids).load

推荐阅读