I have an
Item model
class Item < ActiveRecord:Base
has_and_belongs_to_many :orders
end
And an Order model
class Order < ActiveRecord:Base
has_and_belongs_to_many : items
end
An order can have many items, which the HABTM will take care of. But where/how do I store the quantity of the items that are being ordered?
Eg:
Lets say Order1 has Item1 and Item2 in it. Now i want to store the quantity associated with the items like Order1 has two Item1 and five Item2.
What is the rails way to do this?
One way you could do it would be to use a has_many :through association. This creates an independent entity for your join table between orders and items. In your case:
This would solve your problem I believe. That way Order1 which is associated with Item1 would have a quantity of 2 in the Invoice table and the same with Item2 having a separate quantity of 5 in the Invoice table.
You can read more about these relationships in the The has_many :through Association section in A Guide to Active Record Associations.