2010-06-15 63 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