Bry*_*Ash 2 ruby-on-rails arel ruby-on-rails-3
鉴于以下型号:
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
Run Code Online (Sandbox Code Playgroud)
如何在Rails 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))
Run Code Online (Sandbox Code Playgroud)
Awg*_*wgy 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
Run Code Online (Sandbox Code Playgroud)
或者你可以直接使用find_by_sql传递SQL .
| 归档时间: |
|
| 查看次数: |
3933 次 |
| 最近记录: |