查找与关联模型(表)至少具有一个关联的所有记录

Ant*_*ine 1 model ruby-on-rails rails-activerecord

假设我有这个:

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
Run Code Online (Sandbox Code Playgroud)

如何进行有效的查询来获取Tree至少具有一个FlowerFruit实例或两者的所有实例?这个想法不是得到那些根本Tree没有的东西。FlowerFruit

Yak*_*kov 5

我会使用这样的查询:

Tree.left_joins(:fruits, :flowers).where('fruits.id IS NOT NULL OR flowers.id IS NOT NULL').distinct
Run Code Online (Sandbox Code Playgroud)

它会产生这样的 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)
Run Code Online (Sandbox Code Playgroud)