【问题标题】:Rails query has_and_belongs_to_many with exact countRails 查询 has_and_belongs_to_many 精确计数
【发布时间】:2020-07-10 21:16:37
【问题描述】:

我有以下设置

class Cake
  has_and_belongs_to_many :ingredients # through a join table 
end

class Ingredient
 # secret_id , optional integer column. 
end

我收到了一些秘密 ID。 我想生成一个返回 Cakes 的查询,前提是我可以得到所有的成分。

Cake A: 
  Ingredient A -> secret id -> 1
  Ingredient B -> secret id -> nil

Cake B: 
  Ingredient C -> secret id -> 3
  Ingredient D -> secret id -> nil

假设我们收到一个带有以下参数的请求:[3,4,5] 我当前的查询看起来像这样

Cake.includes(:ingredients).where(ingredients: { secret_id: secret_id_params + [nil] })

这个问题,它会返回蛋糕 A 和蛋糕 B。 它返回 Cake A,因为它的其中一种成分中的秘密 ID 为零。 我不想退回Cake A,因为我没有找到所有的原料。

【问题讨论】:

    标签: sql ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:

    我猜你只需要这样的东西

      Cake.includes(:ingredients).where 
       ingredients: { secret_id: secret_id_params + 
          [nil] } and count(ingredients) = Ingredients.(
             count(distinct secretid) ) 
    

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      相关资源
      最近更新 更多