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