简体   繁体   中英

How to use redirect_to to get to search page. Issue: err_too_many_redirects

I'm trying to add a search bar to my website and redirect to the search page with an alert if there is no parameter entered.

At the moment, when I click on the search icon it brings me to the search page so I know the path exists. When I add the search method to the ApplicationController I get err_too_many_redirects which means there's an infinite somewhere.

I also tried redirecting to my root page, which works, but the alert doesn't happen.

countries_controller.rb

class CountriesController < ApplicationController
  def search
    if params[:search].blank?
      redirect_to(search_page_path, alert: "Empty field!") and return
      #redirect_to(root_path, alert: "Empty field!") and return
    else

    end
  end
  
end

routes.rb

Rails.application.routes.draw do
  get 'countries/index'
  root 'countries#index'

  get 'countries/search', to: 'countries#search', :as => 'search_page'
end

application.html.erb

      <%= form_tag(search_page_path, :method => "get", class: 'navbar-form navbar-right') do %>
        <div class="input-group">
        <%= search_field_tag :search, params[:search], placeholder: "Search", class: "form-control" %>
          <div class="input-group-btn">
            <%= button_tag "", :class => "btn btn-info glyphicon glyphicon-search", :name => nil %>
          </div>
        </div>
      <% end %>

rake routes

                               Prefix Verb   URI Pattern                                                                              Controller#Action
                      countries_index GET    /countries/index(.:format)                                                               countries#index
                                 root GET    /                                                                                        countries#index
                          search_page GET    /countries/search(.:format)                                                              countries#search

I think I've included all the relevant but I'm very new so let me know if anything is missing.

What you are currently doing is redirecting from the search page to itself recursively, which creates an infinite loop.

As you are already on the search page, you just need to show the alert and not do any further redirects. For showing the alerts, you can use flash messages.

def search
  if params[:search].blank?
    flash.now[:alert] = "Empty field!"
  else
    ...
  end
end

You can read more about flash messages here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM