4

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

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?

I have this:

enter image description here

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

4

1 回答 1

13

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

楷模:

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。在这种情况下,您的控制器和视图可能如下所示:

控制器:

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) %>
于 2013-10-24T08:02:28.190 回答