user8116786
user8116786

Reputation:

How to pass a params from view into controller and save it into a variable?

So I am working on this rails project. I am trying to get an input from the view and pass it into the controller, so it can be saved into a variable for later use.

I have my view layer in /views/welcome/index.html.erb with the following :

<div class="locator-input">
  <%= text_field_tag :user_input %>
  <%= submit_tag "Get started" %>
</div>

and the controller in /controller/welcome_controller.rb

class WelcomeController < ApplicationController
  def index
  end

  def locator
    @user_input = params['user_input']
  end
end

and routes.rb here

Rails.application.routes.draw do

  root 'welcome#index'

end

so when I go ahead and hit submit, I get this error:

Ugly error !

I know this error has something to do with routes.rb but I can't figure out how to fix it.

My ultimate goal is to get user input, pass it into the controller and save it into a variable to I can use it with my model later on.

I will greatly appreciate some guidance from our experts.

Thanks.

Upvotes: 1

Views: 62

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

Wrap the field in a form

<div class="locator-input">
  <%= form_tag locator_welcome_path %>
    <%= text_field_tag :user_input %>
    <%= submit_tag "Get started" %>
  <% end %>
</div>

You also need to create a route

Rails.application.routes.draw do
  resource :welcome, controller: :welcome do
    post :locator
  end

  root 'welcome#index'    
end

This will generate

locator_welcome POST   /welcome/locator(.:format)                                                                                                  welcome#locator

Upvotes: 1

spickermann
spickermann

Reputation: 107142

The route generate with root expects only GET requests. But your form sends a POST request.

To solve this just add the following to your config/routes.rb:

root 'welcome#index'
match '/', to: 'welcome#index', via: [:post]

Upvotes: 2

Related Questions