I am writing a simple accounting system for managing costs. The structure is like this:
Invoice - can have many products
Product - can have many costs, also can act_as_tree
LineItem -
Product
LineItem
LineItem
Product
LineItem
Product
LineItem
LineItem
I had this set up as a has_many and belongs_to for the three classes but think that the following is more appropriate (based upon reading Rails 3 Way – any shortcomings are my lack of understanding; just trying to give context)
Class Invoice < ActiveRecord::Base
has_many :products
has_many :line_items, :through => :products
end
Class Product < ActiveRecord::Base
belongs_to :invoice
belongs_to :line_item
end
class LineItem < ActiveRecord::Base
has_many :products
has_many :invoices, :through => :invoices
end
But I don’t this is working correctly.
if I do the following:
>@i=Invoice.find(1)
>@i.products # this works
>@i.line_items # doesn't work, unidentified method line_items
This is the first time I’m using has_many :through. Is this set up correctly for my data model? Also, is it possible to use it in conjunction with acts_as_tree – I’d like to be able to say:
>@i.line_items
and get back all the line items for that specific invoice. Possible?
thx for help
First a question: What is your relation between
ProductandLineItem: Has 1 product many line items or is 1 and the same line item referenced in many products? The rest of this answer is based on the assumption that every product should have multiple line items.I think your models should be defined like that: