所以说我有这个:
class Tree < ActiveRecord::Base
has_many :fruits
has_many :flowers
end
class Fruit < ActiveRecord::Base
belongs_to :tree
end
class Flower < ActiveRecord::Base
belongs_to :tree
end
如何进行有效的查询,以获取Tree
至少包含一个Flower
或多个Fruit
实例或同时具有这两个实例的所有实例?这个想法是没有得到Tree
没有任何Flower
和Fruit
所有。
我会用这样的查询:
Tree.left_joins(:fruits, :flowers).where('fruits.id IS NOT NULL OR flowers.id IS NOT NULL').distinct
它将产生此SQL:
SELECT DISTINCT "trees".* FROM "trees" LEFT OUTER JOIN "fruits" ON "fruits"."tree_id" = "trees"."id" LEFT OUTER JOIN "flowers" ON "flowers"."tree_id" = "trees"."id" WHERE (fruits.id IS NOT NULL OR flowers.id IS NOT NULL)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句