A
A
ArtemBlueberry2015-06-19 02:11:40
Ruby on Rails
ArtemBlueberry, 2015-06-19 02:11:40

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'

Show_product_to_customer controller
def show_product_to_customer 
    @product = Product.find(params[:id])
  end

line item controller
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

1 answer(s)
A
ArtemBlueberry, 2015-06-20
@ArtemBlueberry

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 'В корзину'

routes.rb
show_product_to_customer controller:
def show_product_to_customer #товар, показываемый пользователю
    @product = Product.find(params[:id])
    @line_item =LineItem.new
  end

Line_items controller:
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 question

Ask a Question

731 491 924 answers to any question