title: Rails has_many association through a belongs_to polymorphic association
body: <p>In my database there are 4 models</p>
  
  <pre><code>class MasterPayment &lt; ActiveRecord::Base
    has_many :payments
  end
  
  class Payment &lt; ActiveRecord::Base
    belongs_to :master_payment
    belongs_to :payable, polymorphic: :true
  end
  
  class TreatmentPlan &lt; ActiveRecord::Base
    has_many :payments, as: :payable
  end
  
  class ArbitraryBillableItem &lt; ActiveRecord::Base
    has_many :payments, as: :payable
  end
  </code></pre>
  
  <p>What i would like to do is set up an association in MasterPayment that will associate payables to master payments.</p>
  
  <p>Currently, the closest i could find was setting up the master payment model as follows</p>
  
  <pre><code>class MasterPayment &lt; ActiveRecord::Base
    has_many :payments
    has_many :treatment_plans, through: :payments, source: :payable, source_type: "TreatmentPlan"
    has_many :arbitrary_billable_items, through: :payments, source: :payable, source_type: "ArbitraryBillableItem"
  
    def payables
      self.treatment_plans + self.arbitrary_billable_items
    end
  end
  </code></pre>
  
  <p>The only problem i have with this is that it doesn't feel like the "correct" way to do it.</p>
  
  <p>The only reason i can see for rails not having a solution to this is because you would presumably have to union the tables to return it in one sql statement.</p>
  
  <p>Is there an alternative way to accomplish this that will make more use of the active record associations?</p>