Check boxes search with Ransack gem

后端 未结 1 855
小鲜肉
小鲜肉 2021-02-04 21:27

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::Associa         


        
1条回答
  •  北海茫月
    2021-02-04 22:15

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

    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) %>
      
      <% @users.each do |i| %>
    • <%= i.name %>
    • <% end %>
    <%= paginate(@users) %>

    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:

    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) %>
      
      <% @users.each do |i| %>
    • <%= i.name %>
    • <% end %>
    <%= paginate(@users) %>

    0 讨论(0)
提交回复
热议问题