There is a button that adds 1 item to the basket:

<%= button_to 'Добавить в корзину', line_items_path(item_id: @item) %> 

line_items_controller:

 def create @cart = current_cart item = Item.find(params[:item_id]) @line_item = @cart.add_item(item) 

Tell me how to implement the ability to set the quantity of goods to be added to the cart and how then this quantity can be changed in the cart.

UPD: Explanation: I mean how to associate with the button a text field in which the quantity of the goods will be entered?

  • I mean how to associate with the button a text field in which the quantity of the goods will be entered? - Metallicolis

1 answer 1

Add a new quantity property to the LineItem model

Further

 def add_product(product_id) current_item = line_items.find_by_product_id(product_id) if current_item current_item.quantity += 1 else current_item = line_items.build(product_id: product_id) end current_item end 

In the migration file

 def up # замена нескольких записей для одного и того же товара в корзине одной записью Cart.all.each do |cart| # подсчет количества каждого товара в корзине sums = cart.line_items.group(:product_id).sum(:quantity) sums.each do |product_id, quantity| if quantity > 1 # удаление отдельных записей cart.line_items.where(product_id: product_id).delete_all # замена одной записью cart.line_items.create(product_id: product_id, quantity: quantity) end end end end