我有以下多态关联...
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})
但我无法弄清楚如何为两者做到这一点。有人可以帮忙吗?
答案 0 :(得分:5)
这应该有效:
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)