Topic: The right way to handle a many-to-many modelling case

I have two models Product and Cart. The Cart has many products and the Products can also be seen to be contained in many Carts. I have used the has_and_belongs_to_many handler and have been able to achieve this relationship. However I have a field which says quantity (As in the quantity of the product that is being added to the cart); I do not know where to put this! In the Product? How will that work in many-to-many scenario.

In traditional modelling approaches, my table would have been:
carts_product with these details:
cart_id
product_id
quantity

But now Rails handles all these with its ORM and Migrations; but how do I still get quantity to be unique to each Order/Product.

Any help is really appreciated

Ozo

Re: The right way to handle a many-to-many modelling case

I recommend that you study the pdf "Agile Web Programming" from Pragprom.  Carts are explained very well along with a bunch of other stuff you will need. The code examples are likely just a cut and paste into your application.

You might want to consider using a plugin like spree from spreecommerce.com which may save you a bunch of work.

Last edited by markhorrocks (2011-09-16 21:06:51)

Re: The right way to handle a many-to-many modelling case

Ok! Thanks a lot. Will do

Re: The right way to handle a many-to-many modelling case

So it seems your trying to achieve an has and belongs to many relationship where the join table has columns other than cart_id and product_id. You could name your table carts_products and add the columns you want and than in cart.rb add:

  has_many :carts_products
  has_many :products, :through => :carts_products

And in product.rb, you can add:

  has_many :carts_products
  has_many :carts, :through => :carts_products

In addition, you will need to create a carts_product.rb file to represent this model. Many rails developers are moving away from has_and_belongs_to_many approach because of it's restrictions on columns other than the foreign key and moving towards the has_many :through option instead which achieves the same thing.

Re: The right way to handle a many-to-many modelling case

Also, in terms of naming convention, it may make more sense to name the model cart_product (since it links to one cart and one product) and do the relationship as follows:

has_many :cart_products
has_many :products, :through => :cart_products

Re: The right way to handle a many-to-many modelling case

Wow! Thanks for this! Saw it quite late, but it was still very helpful. Much appreciated!