rubyactiverecordrandom-seedseed

Generating Total from Seeds? (ActiveRecord)


Right now, I am learning ruby and activerecord, and haven't touched upon rails just yet. I am trying to create a Cart instance with attributes of item, price, quantity, order, and total. I have three tables [carts (which belongs to items and order), items, and order].

While Order is just information of the customer, the Item contains the price while the Cart contains the quantity. The problem is that the item attribute is randomized, and total is a float number. I am trying to figure out how I can get the total from the price. Here is how the seeds look:

One of the Item instances:

Item.create(item: "Pencil", price: 1.99, stock: 300)

Cart instance:

Cart.find_or_create_by(item: Item.all.sample, order: Order.all.sample, quantity: rand(1..10), total: )

I appreciate the help!


Solution

  • item = Item.all.sample
    quantity = rand(1..10)
    total = item.price * quantity.to_f
    Cart.find_or_create_by(item: item, order: Order.all.sample, quantity: quantity, total: total)
    

    You could save the item and the quantity to variables and then find the total my multiplying Item#price by quantity, save that to variable, and use that to set the total when you .find_or_create_by