[英]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.