我有以下多态关联...

class Activity < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :activities, as: :owner
end

class Manager < ActiveRecord::Base
  has_many :activities, as: :owner
end

我正在尝试进行查询,它仅提取所有者(用户或经理)将 visible 设置为 true 的事件。

我发现如果我想为其中一位所有者执行此操作,我可以按如下方式执行此操作...
Activity.joins("INNER JOIN users ON activities.owner_id = users.id").where(:activities => {:owner_type => 'User'}).where(:users => {:visible => true})

但我无法弄清楚如何为两者做到这一点。任何人都可以帮忙吗?

最佳答案

这应该有效:

Activity.
  joins("LEFT JOIN users ON activities.owner_type = 'User' AND
                            activities.owner_id = users.id").
  joins("LEFT JOIN managers ON activities.owner_type = 'Manager' AND
                               activities.owner_id = managers.id").
  where("users.visible = ? OR managers.visible = ?", true, true)

关于ruby-on-rails - 具有多态关联的多重内部连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25283493/

10-11 13:10