Rails 3相当于复杂的SQL查询

时间:2010-06-15 03:16:30

标签: ruby-on-rails ruby-on-rails-3 arel

鉴于以下模型:

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

1 个答案:

答案 0 :(得分:10)

我不确定如何使用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。