I am working on an invoicing application that has several types of charges: Line Items, Adjustments and Interest Charges.
I originally had all these models as a has_many to Invoice, e.g.:
class Invoice < ActiveRecord::Base belongs_to :account has_many :line_items has_many :adjustments has_many :interest_charges end
However, I kept running into issues where I was having to join & sort these things to get a timeline of the invoice.
After going through the Intermediate Rails Course it struck me that his Polymorphic implementation was pretty similar to what I was trying to do.
Would I be better suited using a polymorphic association Charge (w/ the LineItem, Adjustment & InterestCharge under that)?
That would let me keep a better timeline since I can just look at the Charge table.
If I do use Polymorphism there, then what’s the best way to return the subclass object rather than the Charge object?
For example, in the workshop he created a class method like:
class Shout < ActiveRecord::Base belongs_to :content, :polymorphic => true def self.text_shouts where(:content_type => "TextShout") end end
But that returns an array of Shout objects and you have to call .content to get to the TextShout object. How would you set up the relationship so that you could call User.find(1).shouts.text_shouts and get back an array of the TextShout objects?
So in the invoice application… If I called invoice.charges.line_items, I’d like to return an array of LineItem objects rather than an array of Charge objects with “LineItem” as the :chargeable_type. Seems like that’d be a common situation?
Anyway, before I ramble myself out of a response, please take a look at the following gist and opine. Thanks a million.