如何将导航栏搜索路由到特定的索引视图?

How to route navbar search to a specific index view?

我正在尝试实施导航栏搜索并尝试遵循这些解决方案 和 .

不幸的是,我的导航栏搜索仅在 /businesses 索引页上有效,否则无效。搜索提交后,应用程序停留在同一页面上,而不是定向到 /businesses.

我该如何解决这个问题?这是我的相关文件:

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

路线

resources :businesses do
  collection do
    match 'search' => 'businesses#search', via: [:get, :post], as: :search
  end
end

_header 部分

<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>

您不能在另一个表单中包含一个表单。最外层的表单总是路由到当前页面。

而是将最外层的形式设为 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>