Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 3相当于复杂SQL查询_Ruby On Rails_Ruby On Rails 3_Arel - Fatal编程技术网

Ruby on rails Rails 3相当于复杂SQL查询

Ruby on rails Rails 3相当于复杂SQL查询,ruby-on-rails,ruby-on-rails-3,arel,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 Ingre

鉴于以下模型:

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

我不知道如何使用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

或者您可以直接使用来传递SQL。

您可以使用连接来折射SQL吗?Subselect并不是真正以“rails”的方式存在的,除了通过执行两个查询和使用Ruby,我认为这种方法可以保持代码的可读性,并且任何其他开发人员都很容易理解和快速学习+1您赢得奖金。。。毫无疑问,这是最好的答案!
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