[英]Multiple Inner Joins with Polymorphic Association
I have the following polymorphic association... 我有以下多态关联...
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
I am trying to make a query whereby it only pulls out the activities where the owner (user or manager) has visible
set to true
. 我试图进行一个查询,它只会拉出所有者(用户或经理) visible
设置为true
。
I have figured out that if I want to do this for one of the owners, I can do this as follows... 我已经想通了,如果我想为其中一位业主做这件事,我可以按照以下方式做到这一点......
Activity.joins("INNER JOIN users ON activities.owner_id = users.id").where(:activities => {:owner_type => 'User'}).where(:users => {:visible => true})
But I cannot figure out how to do it for both. 但我无法弄清楚如何为两者做到这一点。 Can anyone help? 有人可以帮忙吗?
This should work: 这应该工作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.