Reputation: 990
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?
Upvotes: 2
Views: 83
Reputation: 2246
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:
class Order < ActiveRecord::Base
has_many :invoices
has_many :items, :through => :invoices
end
class Invoice < ActiveRecord::Base
belongs_to :order
belongs_to :items
#Put in the migration for this table a column for quantity
end
class Item < ActiveRecord::Base
has_many :invoices
has_many :orders, :through => :invoices
end
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.
Upvotes: 2