ruby-on-railsrubyhttp-redirect

Redirect to new view on submit


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>

Solution

  • There'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.