ruby-on-rails - 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 的查询,或者创建我得到的对的临时表并加入表,但没有一个感觉是正确的。
我错过了更简单的方法吗?
解决方案
我认为最简单的解决方案是:
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
推荐阅读
- python - 查找数据框中的异常或偏差。通过绘图比较均值和标准偏差
- visual-c++ - 树数据结构:我无法获得任何数据输出
- javascript - VueX:如何在页面加载时调用 action.js 方法?
- git - 当功能分支上的特定文件夹发生更改时运行作业,否则无论更改如何都在 master 上运行作业
- powershell - 使用过滤器从列表中获取计数的 Powershell 脚本
- javascript - 在表单执行其操作之前,进行 ajax 调用的表单 onsubmit 不会返回。但是适用于mac但不适用于PC
- r - py_call_impl(callable, dots$args, dots$keywords) 中的错误:ValueError: Empty training data
- c# - 强制 SUM 方法在适用于 EF Core 时返回 NULL
- python - 字典之类的字符串到熊猫数据框的列表
- excel - 查找匹配单元格的列号