Ruby on Rails - Getting value from input box and pass to another page
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", :valu开发者_如何学Ce => "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
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.
I recently had this same question. Here's how I solved it (I'm using Rails 5)
This is my form on the home page, which is a static page:
<%= form_tag(new_project_path, method: :get) do %>
<%= text_field_tag :project, params[:name], placeholder: "project name", class: "project-start" %>
<%= submit_tag "Submit" %>
<% end %>
Then on my /projects/new page, here is the part of the form that I needed to have pre populated from the input field on the home page:
<div class="field">
<%= f.label :name, 'Project Name' %>
<%= f.text_field :name, value: params[:project], required: true %>
</div>
精彩评论