简体   繁体   中英

rails - how to add Quantity text_field to Products list in Shopping Cart

I'm quite a newbie to ROR. I'm building Simple Shopping Cart solution for the purpose of practicing so that I don't want to use gems (eg spree).

There is a products list page. By the side of each product, there is add to cart button.

<%= button_to 'Add to Cart', line_items_path(product_id: product), remote: true %> 

This button will go to line_items_controller#create method. Simply the line item will be created or increased by one.

  def create
    session[:counter] = 0

    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product.id) # @cart is actually Cart Model

    ...
  end

My question is how would I add Quantity text_field beside of add to cart button in the products list page. This Quantity text_field will also be posted to line_items_controller#create method but the line item will be created with this quantity.

I confuse that if I use form helper, which model object do I need to reference in this situation. Is there any other ways to add text_field without using form_helpers? Can you suggest the best way to solve this situation?

I know this may be very naive question but I was really confused for about 3 hours. Please, guide me.

You can use text_field_tag

Add this to your form:

<%= text_field_tag 'quantity' %>

Then access quantity as a parameter in your create action:

quantity = params[:quantity]

Make sure to whitelist the quantity parameter. In Rails 4:

def line_item_params
   params.require(:line_item).permit(:quantity)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM