Search code examples
ruby-on-railsruby-on-rails-5ruby-on-rails-5.1

form_with search field in Rails 5.1


In Rails 5.1 all the forms have to be done with form_with. In http://edgeguides.rubyonrails.org/5_1_release_notes.html#unification-of-form-for-and-form-tag-into-form-with I can only find examples for forms which are related to models.

What is the correct way for this Rails 5.0 form to be done in Rails 5.1 with form_with?

<%= form_tag("/search", method: "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>

Solution

  • Here is form_with call, that is exact equivalent to the form_tag call from the question:

    <%= form_with url: '/search', method: :get, local: true do |f| %>
      <%= f.label :q, "Search for:" %>
      <%= f.text_field :q, id: :q %>
      <%= f.submit "Search" %>
    <% end %>
    

    Note that form_with is sent via XHR (a.k.a remote: true) by default, and you have to add local: true to make it behave like form_tag's default remote: false.

    See more about it in rails guides, API docs and this github issue discussion.