2010-06-15 3 views
2

의 3 동등한 :레일 다음과 같은 모델을 감안할 때 복잡한 SQL 쿼리

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 

가 어떻게 레일 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)) 
+0

조인을 사용하면 굴절시킬 수 있습니까? subselects 정말 두 가지 쿼리를 수행하고 루비, IMO를 사용하여 제외하고 "레일"방식으로 존재하지 않는다 –

답변

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을 통과 할 수있다.

+0

나는이 방법을 생각하고, 그것은 매우 읽기 쉬운 코드를 유지하고 다른 dev에 대해 쉽게 이해하고 빨리 데리러. +1 – StevenMcD

+0

당신은 보너스를 얻습니다 ... 최고의 답을 질문하지 않고! –