2

次のモデルがあるとします。

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

1 に答える 1

10

Arel または ActiveRecord を使用してリレーショナル除算を行う方法がわかりません。2 つのクエリを実行することが許容される場合、これは同等になります。

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 を直接渡すこともできます。

于 2010-06-15T05:51:43.293 に答える