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 request where it only pulls in activities where the owner (user or manager) is visible

set to true

.

I found out that if I want to do it for one of the owners, I can do it like this ...

Activity.joins("INNER JOIN users ON activities.owner_id = users.id").where(:activities => {:owner_type => 'User'}).where(:users => {:visible => true})

      

But I can't figure out how to do this for both. Can anyone please help?

+3


source to share


1 answer


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)

      

+3


source







All Articles