在 Rails Ruby 中按嵌套 ID 和值组合过滤 activerecord
Filter activerecord by nested ID and value combination in Ruby on Rails
假设我有两个具有多对多关系的模型:Item 和 属性
现在我有一个属性数组,我想过滤所有属性匹配给定值的项目(假设一个布尔值:property.value = true)
当我尝试时
@items = Item.includes(:properties).where(:properties => {:id => [1,2,3].to_a, :value => true})
我想获取所有 属性(1) 为真 AND 属性(2) 为真的项目,依此类推。但是通过上面的代码,我得到了与 属性 id 相关的所有项目,其中 any 属性 为真。我应该如何更改我的代码?
我希望不要为此使用 gem。
看起来你快到了:
property_ids = [1,2,3]
Item.joins(:properties).
where(:properties => { :id => property_ids, :value => true }).
group('items.id').
having('COUNT(properties.id) >= ?', property_ids.size)
joins
做一个 INNER JOIN
并且当你真的需要连接表时比 includes
更受欢迎。
where
基本上是你已经具备的条件,唯一的变化是不需要在数组上调用 to_a
。
你必须 group
才能在 SQL 中实现 COUNT
。
having
提取至少具有预期数量的 属性 符合条件的行。
假设我有两个具有多对多关系的模型:Item 和 属性
现在我有一个属性数组,我想过滤所有属性匹配给定值的项目(假设一个布尔值:property.value = true)
当我尝试时
@items = Item.includes(:properties).where(:properties => {:id => [1,2,3].to_a, :value => true})
我想获取所有 属性(1) 为真 AND 属性(2) 为真的项目,依此类推。但是通过上面的代码,我得到了与 属性 id 相关的所有项目,其中 any 属性 为真。我应该如何更改我的代码?
我希望不要为此使用 gem。
看起来你快到了:
property_ids = [1,2,3]
Item.joins(:properties).
where(:properties => { :id => property_ids, :value => true }).
group('items.id').
having('COUNT(properties.id) >= ?', property_ids.size)
joins
做一个 INNER JOIN
并且当你真的需要连接表时比 includes
更受欢迎。
where
基本上是你已经具备的条件,唯一的变化是不需要在数组上调用 to_a
。
你必须 group
才能在 SQL 中实现 COUNT
。
having
提取至少具有预期数量的 属性 符合条件的行。