0

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 %>
fez
  • 1,726
  • 3
  • 21
  • 31

1 Answers1

1

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

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Thanks @Зелёный with that form code I am getting the error /Users/Jack/RailsApp/app/views/pages/index.html.erb:4: syntax error, unexpected ',', expecting ')' ...er.append=( text_field_tag(:q), input );output_buffer.safe... ... ^ -- any ideas? – fez Sep 13 '15 at 18:59
  • you have a syntax error. i added an excess brackets. Check updated answer – Roman Kiselenko Sep 13 '15 at 18:59