简体   繁体   English

复选框搜索Ransack gem

[英]Check boxes search with Ransack gem

I need to filter data in a table. 我需要过滤表格中的数据。 To do this, I found meta_search gem. 为此,我找到了meta_search gem。 I installed meta_search and I get this error: 我安装了meta_search,我收到此错误:

uninitialized constantActiveRecord::Associations::ClassMethods::JoinDependency

This is deprecated for Rails 4 (framework that I'm using). 对于Rails 4(我正在使用的框架), 已被弃用。 So, I installed ransack (rails 4 branch) (gem based on meta_search) and works beautifully. 所以,我安装了ransack(rails 4 branch) (基于meta_search的gem)并且工作得很漂亮。 The problem is that I need to use the meta_search's collection_checks method to handle check boxes and this method does not exist in ransack. 问题是我需要使用meta_search的collection_checks方法来处理复选框,并且这种方法在搜索中不存在。 So, the question is: there is a method in ransack similar to collection_checks to manage checkboxes? 所以,问题是:在ransack中有一个类似于collection_checks的方法来管理复选框吗? or how can I do this? 或者我该怎么做?

I have this: 我有这个:

在此输入图像描述

And I want to filter and get rows with cars, bikes or both 我想过滤汽车,自行车或两者的行

I'm not familiar with meta search but in Ransack (in Rails 4) you can use something like this: 我不熟悉元搜索,但在Ransack(在Rails 4中)你可以使用这样的东西:

MODELS: 楷模:

class User < ActiveRecord::Base
  has_many :user_vehicles 
  has_many :vehicles, through: :user_vehicles
end

class UserVehicle < ActiveRecord::Base
  belongs_to :user
  belongs_to :vehicle
end

class Vehicle < ActiveRecord::Base
  has_many :user_vehicles
end

Controller: 控制器:

class UsersController < ApplicationController
  def index
    @q = User.search(params[:q])
    @users = @q.result(distinct: true)
  end
end

View: 视图:

<%= search_form_for @q , url: users_path, :html => { class: 'your-class' } do |f| %>
  <% Vehicle.all.each do |vehicle| %>
     <%= check_box_tag('q[vehicles_id_eq_any][]', vehicle.id ) %>
     <%= vehicle.name %>
  <% end %>
  <%= f.submit "Search" %>
<% end %>

<%= paginate(@users) %>
  <ul>
    <% @users.each do |i| %>
      <li><%= i.name %></li>
    <% end %>
  </ul>
<%= paginate(@users) %>

You can also use gem for pagination if you still don't use one. 如果您仍然不使用宝石,也可以使用宝石进行分页。 I use Kaminari. 我用Kaminari。 In this case your controller and view could look like this: 在这种情况下,您的控制器和视图可能如下所示:

Controller: 控制器:

class UsersController < ApplicationController
  def index
    @q = User.search(params[:q])
    @users = @q.result(distinct: true).page params[:page]
  end
end

View: 视图:

<%= search_form_for @q , url: users_path, :html => { class: 'your-class' } do |f| %>
  <% Vehicle.all.each do |vehicle| %>
     <%= check_box_tag('q[vehicles_id_eq_any][]', vehicle.id ) %>
     <%= vehicle.name %>
  <% end %>
  <%= f.submit "Search" %>
<% end %>

<%= paginate(@users) %>
  <ul>
    <% @users.each do |i| %>
      <li><%= i.name %></li>
    <% end %>
  </ul>
<%= paginate(@users) %>

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

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