简体   繁体   中英

How to implement Ransack gem

I'm trying to have a search form at the header of every web page that will search through the names of all my "products"

I tried to implement ransack gem, but I am not getting the products filtered results. Through my below code, it just fetches all the products in database and displays. I want to display only searched products.

# routes.rb
resources :product do
  collection do
    match 'search' => 'products#search', via: [:get, :post], as: :search
  end
end

# application.controller.rb
before_filter :set_global_search_variable
def set_global_search_variable
  @q = Product.search(params[:q])
  @product_search = @q.result
end

# application.html.erb
<% search_form_for(@q, url: /search, method: :get)  do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

# search_index.erb
<% @product_search.each do |product| %>
  <%= image_tag product.image_url %>
    <%= product.name %>
  <% end %>
<% end %>

view code

= search_form_for @product_searcher || Product.ransack, url: main_app.admin_products_path do |f|

controller code

def index
  params[:q] ||= { }
  @product_searcher = Product.ransack(params[:q])
  @products = @product_searcher.result
end

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