购物车像轨道应用程序



我是一个新的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 随时更新所选的数据库。如果选定,将所选项目添加到订单数据库并汇总订单总额以进行付款?

对不起,菜鸟问题,提前感谢!

我实际上是最近才建立电子商务的,所以这就是我所做的。 我创建了名为CartCartItem的单独模型。您可以将模型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有购物车项目时,它才会运行。正如你所看到的 控制器方法calculate_totals,你基本上遍历你的购物车项目,抓住每个项目的价格,然后乘以销售数量。然后,结果存储在phones_array变量中。

要计算@subtotal,您只需将phones_array的所有元素与.inject相加。您可以通过@subtotal乘以税率来获得@tax_total,并计算@total您只是将@subtotal@tax_total

最新更新