fez
fez

Reputation: 1835

Rails 4 - Passing user input back to view

Rails newbie here looking for some advice.

I have a basic page with a form and a submit button. When the user hits the submit button, I want to display what was inputted back the user on the same page with some appended text. For example, if the user inputs "jack", then underneath the form I want the string "hello jack!" to be displayed.

How do i pass what is submitted in my view to the controller, append some text, then display back to the page? Note: I don't want to store the input in a database.

Here's what I've got so far, any guidance would be great!

Routes.rb

Rails.application.routes.draw do
get 'home' => 'pages#index'
end

My Controller

class PagesController < ApplicationController
def home
end
end

My view

<h1> Enter some text </h1>
<%= form_tag("/home", method: "get") do %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Submit") %>
<% end %>

Upvotes: 0

Views: 758

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

This should work:

controller.rb:

class PagesController < ApplicationController
  def home
    if params[:q].present?
      @input = "hello #{params[:q]}!" 
    end
  end
end

form:

<%= form_tag("/home", method: "get") do %>
  <%= text_field_tag(:q, @input) %>
  <%= submit_tag("Submit") %>

How params works in Rails

Upvotes: 1

Related Questions