仅选择引擎之间的关联

Selecting only associations between engines

我需要获取所有拥有应用程序的用户。 User 是我的核心引擎的一部分,许多其他引擎都在使用它。我想让用户不知道什么在使用它,这就是为什么我不想在我的 User 模型中添加 has_many :training_applications

这是类

module Account
  class User < ActiveRecord::Base

  end
end


module Training
  class TrainingApplication < ActiveRecord::Base

    belongs_to :user, class: Account::User

  end
end

以下显然行不通,因为User没有TrainingApplication的概念:

Account::User.joins(:training_application).distinct

是否有一种优雅的方法来 return 与 TrainingApplication 相关联的 User 对象的独特集合?

我找到的快速解决方案是

Account::User.where(id: Training::TrainingApplication.all.pluck(:user_id))

但我认为有更好的解决方案。

如果您无法向用户添加 has_many :training_applications 关联,以下应该是合适的解决方案:

您可以自己输入连接字符串:

t1 = Account::User.table_name
t2 = Training::TrainingApplication.table_name

Account::User.
joins("INNER JOINS #{t2} ON #{t2}.user_id = #{t1}.id").
group("#{t1}.id")

为了多样性,让我也介绍一下子查询方法:

Account::User.where("id IN (SELECT user_id FROM #{t2})")

我会选择 joins 方法,但我相信这两种解决方案都会比您当前的实施更快。