Ruby on Rails - Getting value from input box and pass to another page

Umer Hassam picture Umer Hassam · Mar 25, 2011 · Viewed 17.6k times · Source

I have to pass the value of an input field to another page where it will add this value to the database.

The code looks like this

    .shoping_cart_col2
      %input.cart_box{:type => "text", :value => "1"}/
    .shoping_cart_col3 
      = button_to "Add To Cart" , line_items_path(:product_id => @prod)

When i press the "Add to Cart" button i want the value of cart_box to be submitted to the next page with it, this value will be passed to the next page as :quantity

Answer

Viacheslav Molokov picture Viacheslav Molokov · Mar 25, 2011

First of all you need some name for input field, so Rails can find it and pass to params hash.

.shoping_cart_col2
  %input.cart_box{:name => 'item_amount', :type => "text", :value => "1"}

From now in your controller you can get this value with:

# Somewhere in ItemLinesController
def some_action
  ...
  @quantity = params[:item_amount].nil? ? 1 : params[:item_amount]
  ...
end

And now it should be accessible from next page's view via @quantity variable.