Rails 3 相当于复杂的 SQL 查询

发布于 2024-09-05 06:55:15 字数 678 浏览 4 评论 0原文

给定以下模型:

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))

Given the following models:

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

How can I perform the following SQL query using Arel in Rails 3?

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))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我爱人 2024-09-12 06:55:15

我不知道如何使用 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

I am not sure how to do relational division using Arel or ActiveRecord. If it is acceptable to do two queries, this would be equivalent:

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

Or you could just pass the SQL directly using find_by_sql.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文