![](/img/trans.png)
[英]Spree, Ruby on Rails - Add to cart multiple variants of the same product
[英]Add to cart buttons in catalogue (Ruby on Rails, Spree gem)
如何为目录中的每个产品添加添加到购物车按钮? 我创建了链接
<%= 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
我没有任何错误,但由于某种原因产品没有添加到购物车。
如果你看一下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
感谢指针@gmacdougall。 只想添加我如何解决它:
1)复制部分_cart_form.html.erb
(在frontend/app/views/spree/products
文件夹中找到它并将其重命名为_quick_cart_form.html.erb
。这个新文件仍应放在与_cart_form.html.erb
相同的目录中_cart_form.html.erb
。
2)在第_products.html.erb
部分(在frontend/app/views/spree/shared
- 这部分循环通过产品并显示它们)中包含此部分。包含代码应该看起来像<%= render :partial => 'spree/products/quick_cart_form', locals: { product: product } %>
3)注意局部变量product
被传递给partial。 这很重要,因此add to cart方法随产品对象一起提供。
4)将新_quick_cart_form.html.erb
中@product
所有实例重命名为product
(仅匹配提供的局部变量),并隐藏/自定义此新部分中所需的任何div。
这应该允许您直接从产品索引页面(例如类别页面)将产品添加到购物车。
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.