购物车中仅添加了一个产品变体,并且它始终是添加到我的数据库中的第一个产品变体

问题描述

我正在建立一个没有用户系统的简单在线商店-只是购物车之后的一个会话。 目前,我可以选择一个产品(可以认为是产品类别),然后在该产品页面中选择一个属于它的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 (将#修改为@)