ruby-on-rails - 是否有用于按属性分组并查找具有两个不同属性的组的 Ruby/Rails 子句?
问题描述
我有Sandwich
很多
我希望将它们分组:user_id
该user_id
组至少有一个三明治jelly
和一个peanut butter
我最好的尝试是:
Sandwich.group(:user_id).having('topping = ? AND topping = ?', "jelly", "peanut butter")
但我认为语法更适合计数。
这些将是我想要的比赛..
[
[user_id: "X123", topping: "peanut_butter"],
[user_id: "X123", topping: "jelly"]
],
[
[user_id: "Y444", topping: "peanut_butter"],
[user_id: "Y444", topping: "jelly"],
[user_id: "Y444", topping: "jelly"]
]
解决方案
您可以使用内部联接在 SQL 中实现此目的:
SELECT DISTINCT sandwiches.user_id
FROM sandwiches
INNER JOIN sandwiches sandwiches_alias
ON sandwiches.user_id = sandwiches_alias.user_id
WHERE sandwiches.topping = "jelly"
AND sandwiches_alias.topping = "peanut butter";
这将只返回相关的 user_ids。
使用这些数据,您可以使分组查询更加简单:
user_ids = Sandwich.connection.execute(the_above_sql).flatten
Sandwich.where(user_id: user_ids).group(:user_id)
推荐阅读
- javascript - 使用数组属性设置 React 或 Recoil 状态对象的更简单方法
- javascript - 使用 vue.js 提高表列上悬停效果的反应性/性能
- javascript - 如果 data-attribut 等于 0,“parents().filter”返回未定义
- python - 具有许多值的 Python Dash 下拉列表
- cmd - 卸载 anaconda 后 Cmd 崩溃,退出代码为 1
- python-3.x - 为什么通过 boto 将文件上传到 s3 会受到限制?我怎样才能让它更快?
- javascript - 如何构造循环以检查嵌套数组中是否不存在对象值
- javascript - 在玩笑测试中忽略某些导入函数的最佳方法
- python - Big Sur 上的 2019 Macbook Pro + 最新版 Spyder 上的 Pandas 导入错误
- python - 如何删除Python列表最后一个元素中的字符?