2010-06-15 31 views
2

鑑於以下型號:Rails 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 

我如何執行在Rails 3中使用阿雷爾下面的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

你可以折射器使用連接?除了做兩個查詢和使用Ruby,IMO – 2010-06-15 12:26:26

回答

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

以外,子查詢實際上並不存在於「rails」方式中。我認爲這種方法可以讓代碼非常易讀,而且其他開發人員很容易理解並快速獲取。 +1 – StevenMcD 2010-07-23 11:47:04

+0

你贏得獎金...毫無疑問,最好的答案! – 2010-07-27 23:31:09