生成总数从种子? (ActiveRecord)

huangapple go评论58阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月6日 09:09:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定