Spree, Ruby on Rails - Add to cart multiple variants of the same product

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 01:16:07

问题


I want customers to be allowed to add multiple variants of the same product on the same page. Now i have a list of variants with a radio button, how to make them checkboxes? Of course, changing "radio_button_tag" to "check_box_tag" not helping

<% @product.variants_and_option_values(current_currency).each_with_index do |variant, index| %>
  <%= radio_button_tag "products[#{@product.id}]", variant.id, index == 0, 'data-price' => variant.price_in(current_currency).display_price %>
  <%= variant_options variant %>
<% end%>

回答1:


Lets create an example, where the product ID is 1, and you're trying to add variants with id's of 11, and 12.

When you change radio_button_tag to check_box_tag the following parameters will be posted:

products[1]:11
products[1]:12
quantity:1

When this gets interpreted by Rack, it will see that you have 2 variables with the same name, meaning it will choose the last one specified. Your params hash will look something like this:

{
  "products"=>{"1"=>"12"},
  "quantity"=>"1"
}

The simplest modification that you could make to this would be to change your checkbox tag to be:

<%= check_box_tag "products[#{@product.id}][]", variant.id, index == 0, 'data-price' => variant.price_in(current_currency).display_price %>

This will make your hash look like:

The simplest modification that you could make to this would be to change your checkbox tag to be:

{
  "products"=>{"1"=>["11", "12"]},
  "quantity"=>"1"
}

You'll then need to modify this code in the Spree::OrderPopulator to deal with the array passed in (rather than an integer). Something like:

  from_hash[:products].each do |product_id,variant_ids|
    variant_ids.each do |variant_id|
      attempt_cart_add(variant_id, from_hash[:quantity])
    end
  end if from_hash[:products]

And you should be good to go.



来源:https://stackoverflow.com/questions/18288123/spree-ruby-on-rails-add-to-cart-multiple-variants-of-the-same-product

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!