【问题标题】:Add to cart buttons in catalogue (Ruby on Rails, Spree gem)添加到目录中的购物车按钮(Ruby on Rails、Spree gem)
【发布时间】:2013-08-19 00:12:26
【问题描述】:

如何将添加到购物车按钮添加到目录中的每个产品? 我创建了链接

  <%= link_to fast_cart_path do %>
     Add To Cart
  <% end %>

还有行动,OrdersController#update 的副本

  def fast_cart
    populator = Spree::OrderPopulator.new(current_order(true), current_currency)
    if populator.populate(params.slice(:products, :variants, :quantity))
      current_order.create_proposed_shipments if current_order.shipments.any?

      fire_event('spree.cart.add')
      fire_event('spree.order.contents_changed')
      respond_with(@order) do |format|
        format.html { redirect_to cart_path }
      end
    else
      flash[:error] = populator.errors.full_messages.join(" ")
      redirect_to :back
    end
  end

我没有任何错误,但由于某种原因,产品没有添加到购物车中。

【问题讨论】:

    标签: ruby-on-rails shopping-cart spree


    【解决方案1】:

    感谢@gmacdougall 的指点。只是想补充一下我是如何解决的:

    1) 复制部分_cart_form.html.erb(在frontend/app/views/spree/products 文件夹中找到它并将其重命名为_quick_cart_form.html.erb。这个新文件仍应放在与_cart_form.html.erb 相同的目录中。

    2) 在您的 _products.html.erb 部分中包含此部分(在 frontend/app/views/spree/shared 中找到 - 此部分循环通过产品并显示它们)在第 35 行附近。包含代码应类似于 &lt;%= render :partial =&gt; 'spree/products/quick_cart_form', locals: { product: product } %&gt;

    3) 注意局部变量product 被传递给局部变量。这很重要,因此添加到购物车方法与产品对象一起提供。

    4) 将新的 _quick_cart_form.html.erb 部分中的所有 @product 实例重命名为 product(与提供的局部变量匹配),并隐藏/自定义此新部分中所需的任何 div。

    这应该允许您直接从产品索引页面(例如类别页面)将产品添加到购物车。

    `

    【讨论】:

    • 这太棒了!但是由于现在我正在运行同一模板的不同实例,我该如何为 js 做同样的事情,特别是 products.js?
    【解决方案2】:

    如果您查看 Spree::OrderPopulator 中的代码: https://github.com/spree/spree/blob/v2.0.4/core/app/models/spree/order_populator.rb#L20

    您会看到它从传入的散列中获取变量,并尝试在散列中添加从产品或变体传入的任何内容。

    你上面的代码接受

    params.slice(:products, :variants, :quantity)
    

    这是正确的,但是,您指定的链接不会将任何产品或变体添加到参数中。因此,它尝试什么都不添加,什么都不添加成功,然后继续。

    你应该看看 Spree 中更新订单的代码:

    https://github.com/spree/spree/blob/v2.0.4/frontend/app/views/spree/orders/edit.html.erb#L14

    或将新产品添加到购物车的代码:

    https://github.com/spree/spree/blob/v2.0.4/frontend/app/views/spree/products/_cart_form.html.erb

    如果您打开它们并查看其中发生了什么,您应该对如何将产品添加到购物车有更好的了解。


    另一种选择是查看 Spree API 并使用此调用将订单项添加到您的订单中:

    http://api.spreecommerce.com/v1/order/line_items/#creating-a-line-item

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多