英文:
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!
英文:
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!
答案1
得分: 1
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)
你可以将物品和数量保存到变量中,然后通过将Item#price与数量相乘来找到总价,保存到变量中,然后在.find_or_create_by
中使用它来设置总价。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论