本文介绍了使用 Ransack gem 进行复选框搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要过滤表格中的数据.为此,我找到了 meta_search gem.我安装了 meta_search,但出现此错误:

I need to filter data in a table. To do this, I found meta_search gem.I installed meta_search and I get this error:

uninitialized constantActiveRecord::Associations::ClassMethods::JoinDependency

已弃用 Rails 4(我正在使用的框架)).所以,我安装了 ransack(rails 4 分支)(基于 meta_search 的 gem)并且工作精美.问题是我需要使用 meta_search 的 collection_checks 处理复选框的方法,并且ransack 中不存在此方法.那么,问题来了:ransack 中有一种类似于 collection_checks 的方法来管理复选框吗?或者我该怎么做?

This is deprecated for Rails 4 (framework that I'm using). So, I installed ransack (rails 4 branch) (gem based on meta_search) and works beautifully. 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. So, the question is: there is a method in ransack similar to collection_checks to manage checkboxes? or how can I do this?

我有这个:

我想过滤并获取包含汽车、自行车或两者的行

And I want to filter and get rows with cars, bikes or both

推荐答案

我不熟悉元搜索,但在 Ransack(在 Rails 4 中)你可以使用这样的东西:

I'm not familiar with meta search but in Ransack (in Rails 4) you can use something like this:

型号:

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

控制器:

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

查看:

<%= 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) %>

如果您仍然不使用 gem,您也可以使用 gem 进行分页.我用 Kaminari.在这种情况下,您的控制器和视图可能如下所示:

You can also use gem for pagination if you still don't use one. I use Kaminari. In this case your controller and view could look like this:

控制器:

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

查看:

<%= 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) %>

这篇关于使用 Ransack gem 进行复选框搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 13:01