Search code examples
ruby-on-railsformsfieldtemp

Create a non-database linked form field in ruby on rails


I am attempting to do some calculations on a simple ruby screen. Lets say for fun, i want to create a form that lets the user convert meters to feet. Of course I don't want to store the values in a database. Nor would I want to create a table just for this.

So my question.. How do I create a single text field tied to a controller. With a button.


Solution

  • Here's a really simple example of making a form adding two numbers:

    rails new math_app -O
    cd math_app
    rails generate controller Add form result
    

    The last line generates a controller with 2 actions -

    • "form"- to show the form
    • "result" - to show the results

    In another command prompt window, open the 'math_app' directory and start the server:

    rails server
    

    You can open a browser to 'localhost:3000/add/form' and 'localhost:3000/add/result' to see the default pages Rails generated for you. As you edit things below you can revisit these pages (and don't even have to restart the server) to see what they produce.

    Edit 'app\views\add\form.html.erb' to create the form we want to show.

    <%= form_tag add_result_path do %>
      <%= number_field_tag :first %>
      +
      <%= number_field_tag :second %>
      <%= submit_tag "add" %>
    <% end %>
    

    Edit 'config/routes.rb' to make the 'result' action take POST requests from the form above.

    Change -

    get "add/result"
    

    to-

    post "add/result"
    

    Edit 'app\controllers\add_controller.rb' result method to retrieve the two numbers from the form data and add them together.

    def result
      @first = params[:first].to_i
      @second = params[:second].to_i
      @result = @first + @second
    end
    

    Edit 'app\views\add\result.html.erb' to show the result.

    <%= @first %> + <%= @second %> = <%= @result %>
    <br/>
    <%= link_to 'back', add_form_path %>
    

    Done!