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 中使用 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))
Given the following models:
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
How can I perform the following SQL query using Arel in Rails 3?
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道如何使用 Arel 或 ActiveRecord 进行关系划分。如果可以接受执行两个查询,则这将是等效的:
或者您可以使用 find_by_sql。
I am not sure how to do relational division using Arel or ActiveRecord. If it is acceptable to do two queries, this would be equivalent:
Or you could just pass the SQL directly using find_by_sql.