【问题标题】:Rails where has related model with specific valuesRails 具有具有特定值的相关模型
【发布时间】:2018-08-17 12:54:21
【问题描述】:

我有一个食谱模型,它通过 recipe_ingredients 包含许多成分。

我怎样才能有效地获得所有的食谱

  • 吃黄油和巧克力
  • 吃黄油但不吃巧克力
  • 既没有黄油也没有巧克力

会有数百万个食谱,所以我希望只用一个查询就能得到我需要的结果,而不必在第一个条件的结果中进行选择或拒绝。 喜欢:

Recipe.joins(:ingredients)
  .where(ingredients: { name: 'chocolate' })
  .select{ |recipe| recipe.ingredients.pluck(:name).include?('butter') }

另外,当用户选择超过 2 种成分时,我需要它来工作。 我愿意以不同的方式存储数据,如果这样可以提高搜索效率 - 或者使用直接的 sql 查询。

谢谢

【问题讨论】:

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


    【解决方案1】:

    对于有黄油和巧克力的食谱:

    Recipes.joins(:ingredients)
      .where(ingredients: { name: ['chocolate','butter'] })
    

    对于有黄油但没有巧克力的食谱:

    Recipes.joins(:ingredients)
      .where(ingredients: { name: 'butter' })
      .where.not(ingredients: { name: 'chocolate' })
    

    对于既没有黄油也没有巧克力的食谱:

    Recipes.joins(:ingredients)
      .where.not(ingredients: { name: ['chocolate', 'butter'] })
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多