我是一名新的 Rails 开发人员,正在构建一个提供干洗送货服务的网站。
用户将选择他们想要取走的元素数量,裤子、衬衫等。
这是我的表格:
create_table "products", force: :cascade do |t|
t.string "name"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "product_type"
t.text "image"
end
所有产品都保存在数据库中。我希望每个用户都可以在订单页面上选择衣服的数量和类型以及数量。
我将如何添加订单总计并将交易添加到所有所选项目的最近订单历史记录中?
我相信我将需要 jquery 来更新选中项目后始终选择的数据库。将所选项目添加到订单数据库(如果选择)并汇总订单总额以进行付款?
抱歉,菜鸟问题,提前致谢!
最佳答案
实际上,我最近才建立电子商务,所以这就是我所做的。
我创建了名为 Cart
的单独模型和 CartItem
.您可以切换模型 Phone
至 Product
(或用于存储与产品相关的信息的任何模型(即:价格、可用数量等)
class CartItem < ApplicationRecord
belongs_to :cart, {:optional => true}
belongs_to :phone, {:optional => true}
end
class Cart < ApplicationRecord
has_one :user
has_many :cart_items
end
class Phone < ApplicationRecord
has_many :cart_items
end
Cart
模型没有属性。它的主要目的只是用来存放不同的购物车元素。
CartItem
模型有一个它属于哪个购物车的外键(cart_id
)以及它在哪个手机上的外键(phone_id
)(你可以将它切换到衣服)。每个购物车项目只能有一部电话,以及该电话的相应数量。因此,您可以循环 @user.cart.cart_items
并获取每件衣服以及与每件衣服相关的数量。
模型所需的属性 CartItem
:
t.integer "cart_id"
t.integer "phone_id"
t.integer "quantity_sold"
因此,使用这些模型及其各自的属性,您可以通过 calculate_total
计算总数每次进入购物车页面时运行的方法:
def calculate_totals
phones_array = []
if @user.cart.cart_items.present?
@user.cart.cart_items.each do |item|
phone_total = item.phone.price * item.quantity_sold
phones_array << phone_total
end
@subtotal = phones_array.inject{|memo,n| memo + n}
@tax_total = @subtotal * 0.13
@total = @subtotal + @tax_total
end
end
def cart
calculate_totals
end
请注意,它只会在 @user
时运行有购物车元素。如您所见, Controller 方法 calculate_totals
,您基本上遍历了您的购物车商品,获取每件商品的价格并将其乘以销售数量。然后将结果存储在 phones_array
中变量。
计算@subtotal
,您只需添加 phones_array
的所有元素即可与 .inject
.你得到 @tax_total
通过乘以 @subtotal
按税率计算@total
你只是添加 @subtotal
通过 @tax_total
.
关于ruby-on-rails - 像 Rails 应用程序一样的购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258869/