Search code examples
ruby-on-railsrubyruby-on-rails-4

How can I pass the text input into a form as part of params?


If I set my routes up like this for example:

resources :articles do
  member do
    get :search
  end
end

What should the form look like to get params[:search] to the search method of ArticlesController? I've been trying variations of this but can't get it to work:

<%= form_for search_article_path, :method => :get do |f| %>
  <%= f.label :search %>
  <%= f.text_field :search %>

  <%= f.submit :submit %>
<% end %>

Solution

  • Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in _tag (such as text_field_tag and check_box_tag), generate just a single <input> element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the params hash in the controller with the value entered by the user for that field. For example, if the form contains <%= text_field_tag(:query) %>, then you would be able to get the value of this field in the controller with params[:query].

    If you have trouble with params you can check this video out: https://gorails.com/episodes/the-params-hash