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