I'm looking to create a search bar that works in any page to find items in my movies database. I have the search bar only working when I'm already in the movies index page, but it doesn't work in any other page, it only reloads the current view with the search on the path. How could I redirect to the movies index page when I submit my search?
<form class="d-flex">
<%= form_tag movies_path, method: :get do %>
<%= text_field_tag :search, params[:search], class:"form-control me-2", placeholder:"Search" %>
<%= submit_tag "Search", :title => nil, class:"btn btn-outline-primary" %>
<% end %>
</form>
I'm looking to create a search bar that works in any page to find items in my movies database. I have the search bar only working when I'm already in the movies index page, but it doesn't work in any other page, it only reloads the current view with the search on the path. How could I redirect to the movies index page when I submit my search?
<form class="d-flex">
<%= form_tag movies_path, method: :get do %>
<%= text_field_tag :search, params[:search], class:"form-control me-2", placeholder:"Search" %>
<%= submit_tag "Search", :title => nil, class:"btn btn-outline-primary" %>
<% end %>
</form>
Share
Improve this question
asked Mar 28 at 11:20
JMSJMS
153 bronze badges
2
|
2 Answers
Reset to default 0There's mess in your view code: double form (first in plain html, second is rails form_tag
). Simply remove double form tag.
<%= form_tag movies_path, method: :get do %>
<%= text_field_tag :search, params[:search], class:"form-control me-2", placeholder:"Search" %>
<%= submit_tag "Search", :title => nil, class:"btn btn-outline-primary" %>
<% end %>
In rails you should use form_tag
, or form_with
, or form_for
or even gems like simple_form
for extra functionality.
They have different signature (input params) and usecases, please refer to documentation to choose the one you need.
Nested form elements are not permitted in any HTML version. As this is invalid markup the brower can choose to ignore the inner form tag completely.
The modern way to write this code would be:
<%= form_with url: movies_path, method: :get do |form| %>
<%# Do not use placeholders instead of labels. %>
<%= form.label :search %>
<%= form.text_field_tag :search, params[:search], class:"form-control me-2" %>
<%= form.submit_tag "Search", title: nil, class: "btn btn-outline-primary" %>
<% end %>
form_with
replaces the the legacy form_tag
helper method and has the same signature no matter if you're binding the form to a model instance or not.
Using <%= form.text_field_tag
to call the helpers on the form builder instance yeilded to the block let's you easily refactor the code into using a form object and use features like I18n.
form
tag? – mechnicov Commented Mar 28 at 11:23