How to use Ransack in navbar search form?

£可爱£侵袭症+ 提交于 2020-01-15 11:07:07

问题


I am using Ransack with Rails 5 to search images in gallery by their descriptions. Search form is located in navbar, and Ransack gives me results only when I'm displaying images gallery page. Searching don't return any result when I display any other pages including the same navbar.

My code from _header.html.erb:

<div class="form-group">
  <%= search_form_for @q, url: search_pins_path, html: { method: :post } do |f| %>
    <%= f.search_field :description_cont, type: "text", class: "form-control", placeholder: "Search" %>

     <%= f.submit 'Search', class:"btn btn-default"%>
   <% end %>
 </div>

application_controller.rb:

class ApplicationController < ActionController::Base
 protect_from_forgery with: :exception

 before_action :set_global_search_variable

 def set_global_search_variable
  @q = Pin.ransack(params[:q])
 end
end

How to get results from Ransack searching during displaying any other page from the same navbar?


回答1:


Add to your routes:

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

In application.controller:

before_action :set_global_search_variable

def set_global_search_variable
  @q = Pin.search(params[:q])
end

def search
 index
 render :index
end

And in pins controller:

  def index
    @pins = @q.result
  end


来源:https://stackoverflow.com/questions/52477309/how-to-use-ransack-in-navbar-search-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!