I'm trying to implement a navbar search and have attempted to follow these solutions https://stackoverflow.com/a/19929707/5101493 and https://stackoverflow.com/a/52538766/5101493.
Unfortunately my navbar search only works when on the /businesses
index page and not otherwise. After search submission the app stays on the same page instead of directing to /businesses
.
How can I fix this? Here are my relevant files:
application_controller
before_action :set_global_search_variable
def set_global_search_variable
@p = Business.search(params[:q])
end
businesses_controller
def index
@businesses = @p.result(distinct: true).sort_by(&:name)
end
def search
index
render :index
end
routes
resources :businesses do
collection do
match 'search' => 'businesses#search', via: [:get, :post], as: :search
end
end
_header partial
<form class="form-inline" style='display:show'>
<%= search_form_for @p , url: search_businesses_path, :html => { method: :post } do |f| %>
<%= f.search_field :name_cont, {placeholder: " Find a business...", class: 'form-control mr-sm-2'} %>
<%= f.submit "Search", class: "btn look-red my-2 my-sm-0 navsearch" %>
<% end %>
</form>
You can't have a form inside another form. The outermost form is always routing to the current page.
Instead make the outermost form a div.
<div class="form-inline" style='display:show'>
<%= search_form_for @p , url: search_businesses_path, :html => { method: :post } do |f| %>
<%= f.search_field :name_cont, {placeholder: " Find a business...", class: 'form-control mr-sm-2'} %>
<%= f.submit "Search", class: "btn look-red my-2 my-sm-0 navsearch" %>
<% end %>
</div>