Не получается сохранить количество товара при добавлении в корзину
Я пытаюсь создать корзину покупок для интернет-магазина. На странице товара находится кнопка "Add to cart", по нажатию на которую создается line_item и добавляется в cart.
Я хочу сделать так, чтобы на этой же странице рядом с кнопкой я мог выбрать количество товара, добавляемого в line_item, а затем и в cart, соответственно.
Код контроллера
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
def new
@line_item = LineItem.new
end
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product)
@line_item.quantity = params['q'].to_i
if @line_item.save
redirect_to @line_item.cart, notice: 'Item added to cart.'
else
render :new
end
end
private
def line_item_params
params.require(:line_item).permit(:product_id, :quantity)
end
end
Код представления view/products/show.html.erb
<section class="section instrument-show">
<div class="columns">
<div class="column is-8">
<h1 class="title is-2"><%= @product.title %></h1>
<h3 class="subtitle is-4">Description</h3>
<%= @product.description %>
</div>
<div class="column is-3 is-offset-1">
<div class="bg-white pa4 border-radius-3">
<h4 class="title is-5 has-text-centered"><%= number_to_currency(@product.price) %></h4>
<form>
<input type="number" name="q" min="1" max="50" step="1" class="input label">
</form>
<%= button_to 'Add to cart', line_items_path(product_id: @product), class: 'button is-warning add-to-cart' %>
</div>
</div>
</div>
</section>
При таком варианте кода в контроллере в params['q'] я получаю "nil", а после .to_i - ноль. Почему форма
<form>
<input type="number" name="q" min="1" max="50" step="1" class="input label">
</form>
не передаёт в контроллер этот параметр?
Подскажите, пожалуйста, кто-нибудь как мне в LineItemsController получить вводимое на странице товара число (количество покупаемого товара).
Метод add_product
def add_product(product)
current_item = line_items.find_by(product_id: product.id)
if current_item
current_item.increment(:quantity)
else
current_item = line_items.build(product_id: product.id)
end
current_item
end
Ответы (1 шт):
Вам нужно сделать так, чтобы кнопка "Add to cart" отправляла форму
<%= form_with model: LineItem.new, local: true %>
<%= form.hidden_field :product_id, value: @product.id %>
<%= form.number_field :quantity, min: 1, max: 50, step: 1, class: "input label" %>
<%= form.submit 'Add to cart', class: "button is-warning add-to-cart" %>
<% end %>
Теперь параметр quantity попадает в параметры контроллера и с ним можно работать. Он у вас уже есть в permitted params, проще всего ими и воспользоваться для создания нового line_item
def create
@line_item = @cart.line_items.build(line_item_params)
if @line_item.save
redirect_to @cart, notice: 'Item added to cart.'
else
render :new
end
end