简体   繁体   English

如何实现Ransack gem

[英]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. 我尝试实施ransack gem,但没有得到产品过滤结果。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM