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
.
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments