Answer the question
In order to leave comments, you need to log in
How to pass selected value from collection select?
Good day.
When developing an online store, a problem arose: I added a size field to the product model, but I can’t make it so that the size selected by the buyer is added to line items.
Tell me how can I make it so that the selected value from the collection select can be passed as an argument to the add to cart function?
Show_product_to_customer view
= @product.title
= collection_select(:product,:size, @product.sizes, :id,:name)
= button_to 'В корзину', line_items_path(product_id: @product,size_id: ??? ),
remote: true, form_class: 'button-cart'
def show_product_to_customer
@product = Product.find(params[:id])
end
def create
@cart = current_cart
product = Product.find(params[:product_id])
size = Size.find(params[:size_id])
@line_item = @cart.add_product(product.id,size.id)
def add_product(product_id,size_id)
current_item = line_items.find_by(product_id: product_id, size_id: size_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(product_id: product_id, size_id: size_id)
end
current_item
end
Answer the question
In order to leave comments, you need to log in
Solved the problem like this:
Show_product_to_customer view:
=form_for @line_item, url: create_line_item_path, html: {method: 'post'} do |f|
=f.hidden_field :product_id, value: @product.id
[email protected]
br
=f.collection_select(:size_id, @product.sizes.all, :id, :name)
=f.submit 'В корзину'
def show_product_to_customer #товар, показываемый пользователю
@product = Product.find(params[:id])
@line_item =LineItem.new
end
def create
@cart = current_cart
size = Size.find(params[:line_item][:size_id])
product = Product.find(params[:line_item][:product_id])
@line_item = @cart.add_product(product.id, size.id)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question