I want to create a simple calculator form in Rails 3.1 just for understanding. Via a form I want to get a number and multiplied it by two (for example).
I’ve created controller with index page (/index), then form in views:
<%= form_for @result do |f|%>
<%= f.label :number, 'Number' %>:
<%= f.text_field :number %>
<%= submit_tag 'Submit' %>
<%end%>
<%=@result%>
What I need to do with controller?
def index
@result = ''
end
def calculate
@result = @number.to_i*2
end
This is not gonna work.
form_foris used to build forms for models that extend ActiveRecord. Useform_tag('/calculate')instead.You need to define `match ‘calculate’ => ‘your_controller_name#calculate’ in config/routes.rb.
Additionally, you need a view for your calculate action –
calculate.html.erb(you can call it differently but you’ll have to specifyrender 'view_name'.Alternatively, if you want to use the same view file, use
render :action => :indexForgot to mention.
To access the data from the form, you use
params[:key]hash.So in your case it would look like
@result = params[:number] * 2This book is a great place to start with Rails.
Also, these screencasts are pretty helpful too