How to make this active record associations

I have an

Item model

class Item < ActiveRecord:Base
  has_and_belongs_to_many :orders

And an Order model

class Order < ActiveRecord:Base
   has_and_belongs_to_many : items

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:

class Order < ActiveRecord::Base
  has_many :invoices
  has_many :items, :through => :invoices

class Invoice < ActiveRecord::Base
  belongs_to :order
  belongs_to :items

  #Put in the migration for this table a column for quantity

class Item < ActiveRecord::Base
  has_many :invoices
  has_many :orders, :through => :invoices

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.

Need Your Help

How to share EntityFramework 6 datacontext without using repositories?

c# entity-framework

As EF6 is now fully mockable and we have the unit of work and repository built in - I'd like to move away from repository pattern.

How do you get a UI button to do different tasks each time it is pressed?

ios swift ios8 xcode6

When I create an IBaction for a button I can easily get it to perform an action for example: