gpt4 book ai didi

ruby-on-rails - Rails 3 等同于复杂的 SQL 查询

转载 作者:行者123 更新时间:2023-12-04 03:36:34 24 4
gpt4 key购买 nike

给定以下模型:

class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
end

class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end

class Ingredient < ActiveRecord::Base
end

如何在 Rails 3 中使用 Arel 执行以下 SQL 查询?

SELECT * FROM recipes WHERE NOT EXISTS (
SELECT * FROM ingredients WHERE
name IN ('chocolate', 'cream') AND
NOT EXISTS (
SELECT * FROM recipe_ingredients WHERE
recipe_ingredients.recipe_id = recipes.id AND
recipe_ingredients.ingredient_id = ingredients.id))

最佳答案

我不确定如何使用 Arel 或 ActiveRecord 进行关系除法。如果可以接受执行两个查询,则这将是等效的:

with_scope(includes(:recipes)) do
cream_recipes = Ingredient.where(:name => "cream").first.recipes
chocolate_recipes = Ingredient.where(:name => "chocolate").first.recipes
end
@recipes_with_chocolate_and_cream = cream_recipes & chocolate_recipes

或者您可以直接使用 find_by_sql 传递 SQL .

关于ruby-on-rails - Rails 3 等同于复杂的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3042308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com