如何解决购物车中仅添加了一个产品变体,并且它始终是添加到我的数据库中的第一个产品变体
我正在建立一个没有用户系统的简单在线商店-只是购物车之后的一个会话。 目前,我可以选择一个产品(可以认为是产品类别),然后在该产品页面中选择一个属于它的ProductVariant(product_variant_id)。
问题在于,当我添加不同的product_variant时,只有保存到数据库的第一个变量才添加到购物车中。我可以在下拉菜单中选择product_variants,但同样,只有记录中添加到数据库中的第一个添加到购物车中,作为order_item。
我的相关模型:
Product
has_many :product_variants,dependent: :destroy
has_many :order_items,:through => :product_variants
ProductVariant
belongs_to :product
has_many :order_items,dependent: :destroy
OrderItem
belongs_to :order,optional: true
belongs_to :cart,optional: true
belongs_to :product_variant
belongs_to :product
Cart
has_many :order_items
这是我在show.html.erb中的产品展示页面,可以选择product_variant
<%= link_to products_path do %>
<h4>Back to store gallery</h4>
<% end %>
<section class="flexbox">
<div class="flex">
<%= image_tag @product.image_1.show.url %>
</div>
<div class="flex">
<h2><%= @product.title %></h2>
<div class="product-description">
<h5>Description:</h5>
<p><%= @product.description %></p>
</div>
</div>
</section>
<%= simple_form_for [@product,@product_variant,@order_item] do |f| %>
<%= f.input :quantity %>
<%= f.button :submit,"Add to cart" %>
<% end %>
Product selection: <br>
<select name="product[product_variant_id]">
<% @product.product_variants.each do |product_variant| %>
<option value="<%= product_variant.id %>"><%= product_variant.item %>/<%= product_variant.size %>/<%= product_variant.color %>/<%= number_to_currency product_variant.price_in_dollars %></option>
<% end %>
</select>
最后,这是我的order_items控制器
class OrderItemsController < ApplicationController
def create
@product = Product.friendly.find(params[:product_id])
# find the product_variant
@product_variant = ProductVariant.find(params[:product_variant_id])
# quantity? - comes from the form data
@quantity = form_params[:quantity]
@current_cart.order_items.create(product: @product,product_variant: @product_variant,quantity: @quantity)
flash[:success] = "Thanks for adding to your cart"
redirect_to product_path(@product)
end
def update
@product = Product.friendly.find(params[:product_id])
@product_variant = ProductVariant.find(params[:product_variant_id])
@order_item = OrderItem.find(params[:id])
@order_item.update(form_params)
flash[:success] = "Thanks for updating your cart"
redirect_to cart_path
end
def destroy
@product = Product.friendly.find(params[:product_id])
@product_variant = ProductVariant.find(params[:product_variant_id])
@order_item = OrderItem.find(params[:id])
@order_item.delete
flash[:success] = "Product removed from cart"
redirect_to cart_path
end
def form_params
params.require(:order_item).permit(:quantity)
end
end
感谢您对这里可能出问题的任何见解,如果您需要我提供更多相关的代码,请不要犹豫,
亚伦
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。