timothyylim
timothyylim

Reputation: 1537

Creating an 'order' model made up of 'products' and 'quantities' [rails]

I have a specific question that is also quite general.

I want to create a database entity called 'order' which is made up of 'products' and quantities of the products. I think I have the first few steps done:

First I will create the order and product models

rails g model product
rails g model order
rails g migration createJoinTableProductOrder product order 
rails db:migrate 

How can I seed the database with the following:

  1. Orders that are associated to many products
  2. Information about the quantity of each product in each order

The seeds should be something like this:

Product A 
Product B

Order 1 has 3 of Product A and 2 of Product B
Order 2 has 1 of Product A and 1 of Product B

Any help would be greatly appreciated!

Upvotes: 1

Views: 246

Answers (1)

Waleed Arshad
Waleed Arshad

Reputation: 1099

Let me explain with example

class Product
  has_and_belongs_to_many :orders
end

class Order
 has_and_belongs_to_many :products
end

Creating Order and products

order_1 = Order.create(:name => "Order1")
products_a = 3.each{|i| Product.create(name: "Product_A_#{i}")  }
products_b = 2.each{|i| Product.create(name: "Product_B_#{i}")  }
order_1.products << products_a
order_1.products << products_b

Now for order 2 repeat step

order_2 = Order.create(:name => "Order2")
product_a = Product.create(name: "Product_a")
product_b = Product.create(name: "Product_b") 
order_2.products << products_a
order_2.products << products_b

3rd table Products_orders will automatically be populated. Let me know if you need more explanation. just write same in seed to work. you can add further checks is products or user already exits etc.

Thanks

Upvotes: 3

Related Questions