Steve.NayLinAung Steve.NayLinAung - 8 months ago 55
Ruby Question

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 (e.g. 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( # @cart is actually Cart Model


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.

Answer Source

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