I have an invoicing system that manages debits and credits. Basically the invoice amount is obtained by the sum of its debits and the balance is derived by taking the sum of its credits and subtracting it against the total amount.
I'm doing this with four models.
- Invoice
- Line Item
- Debit
- Credit
The way it works is via a join model (Line Item) that has a polymorphic association called recordable. Everything appears to work properly at first glance. However, inspecting the line item shows that while the recordable_id shows up alright, the recordable_type is nil.
Here is a break down of the code:
class Invoice < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
has_many :debits, :through => :line_items, :as => :recordable
has_many :credits, :through => :line_items, :as => :recordable
end
class LineItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :recordable, :polymorphic => true
belongs_to :credit, :class_name => "Credit", :foreign_key => "recordable_id"
belongs_to :debit, :class_name => "Debit", :foreign_key => "recordable_id"
end
class Credit < ActiveRecord::Base
has_many :line_items, :as => :recordable, :dependent => :destroy
end
class Debit < ActiveRecord::Base
has_many :line_items, :as => :recordable, :dependent => :destroy
end
Can anyone point me into the right direction here?