Brandon
Brandon

Reputation: 21

Rails Has Many Through

So this whole many-to-many thing has me really confused. I get how to set it up but I can't seem to find anywhere that really explains the best way to use it in your controller.

What I have:

Products, Orders, Orders_Products

The Products and Orders table has the standard stuff (Id, name, timestamps, etc)

The Orders_Products table has the two id columns (order_id, product_id) and a quantity column.

What I need to do:

Now when I save my "cart" how do you save a new order and each product with its quantity?

This is my first app in rails so the more explanation the better.

Thanks in advance for all the help!

Upvotes: 2

Views: 541

Answers (1)

Cristian
Cristian

Reputation: 138

To start, you should only have two tables, Orders and Products. Here is a great guide I was given in one of my questions - guides.rubyonrails.org/association_basics.html

Have a read of that to familiarize yourself with associations in rails, but pretty much what you are trying to achieve is the following -

In your order model have the relation

  has_many :products

And in your products model have the relation

  belongs_to :order

That way you can link your products to your orders. Then you can make calls like

  order.products

which will give you all the products for a particular order.

In your migrations you will need to give your products an order_id to make that association between orders and products.

In terms of saving the products to an order, you will do that in your products controller either by associating the order_id in to some form in your view and sending the order id through the params hash, and just write

   product = Product.create(params[:product])

or you can do it in your controller and say

   product.order_id = @order.id

@order can be found from the order id from your url in your products controller, so you just make a method saying

   def find_order
      @order = Order.find(params[:order_id])
   end

and at the top of the controller before any actions you can say

   before_filter :find_order, :only => :youractiontosaveproducts

and what that will do is find the order you are saving the product to before that action is called.

To write all the code in an answer is a bit of overkill, a read of that guide and some practice will get you on the right track :)

Upvotes: 2

Related Questions