繁体   English   中英

Active Record 连接,其中所有连接的记录都不匹配查询字符串

[英]Active Record join where all joined records DO NOT match query string

我有一个包含许多IngredientsRecipe

class Recipe < ApplicationRecord
  has_many :ingredients
end
class Ingredient < ApplicationRecord
  belongs_to :recipe
end

我可以找到包含名称与搜索查询q相似的任何成分的食谱。

Recipe.joins(:ingredients).where('lower(ingredients.name) LIKE ?', "%#{q}%")

这导致以下 output。

Recipe.search('cod')
  Recipe Load (0.9ms)  SELECT DISTINCT "recipes".* FROM "recipes" INNER JOIN "ingredients" ON "ingredients"."recipe_id" = "recipes"."id" WHERE (lower(ingredients.name) LIKE '%cod%' OR lower(recipes.name) LIKE '%cod%')
 => 
[#<Recipe:0x0000000114812300
  id: 227,
  name: "Fish Tacos",
  steps:
   "<div>To make beer batter: In a large bowl, combine flour, cornstarch, baking powder, and salt. Blend egg and beer, then quickly stir into the flour mixture (don't worry about a few lumps).</div><div><br>To make white sauce: In a medium bowl, mix together yogurt and mayonnaise. Gradually stir in fresh lime juice until consistency is slightly runny. Season with jalapeno, capers, oregano, cumin, dill, and cayenne.</div><div><br>Heat oil in deep-fryer to 375 degrees F (190 degrees C).</div><div><br>Dust fish pieces lightly with flour. Dip into beer batter, and fry until crisp and golden brown. Drain on paper towels. Lightly fry tortillas; not too crisp. To serve, place fried fish in a tortilla, and top with shredded cabbage, and white sauce.</div>",
  desc: nil,
  created_at: Sat, 24 Dec 2022 16:03:44.122092000 UTC +00:00,
  updated_at: Sat, 24 Dec 2022 16:05:53.886182000 UTC +00:00>]

SQL

SELECT DISTINCT "recipes".* FROM "recipes" INNER JOIN "ingredients" ON "ingredients"."recipe_id" = "recipes"."id" WHERE (lower(ingredients.name) LIKE '%cod%' OR lower(recipes.name) LIKE '%cod%')

我怎么能做相反的事情呢? 如果我想搜索任何包含奶酪、牛肉等的食谱,我该如何更改 ActiveRecord 连接,其中 NOT 用于每个关联记录。

换句话说,我如何更改查询以返回Recipes ,其中没有任何成分的名称与查询q匹配?

使用当前方法,我一直在尝试取回每个Recipe ,因为每个食谱至少有一种与查询不匹配的成分。

Recipe.joins(:ingredients).where('ingredients.name NOT LIKE ?', 'cheese')

提前致谢!

Recipe.where(
 Ingredient.where('ingredients.name LIKE %?%',  'cheese')
           .where(Ingredient.arel_table[:recipe_id].eq(Recipe.arel_table[:id]))
           .arel
           .exist
           .not
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM