mardi 5 juin 2018

How Implement filters on my users index?

I work on an application and I try to implement a filter for my users index. I try a lot of solutions on the web but not successfully. I need to filter with mother_tongue, locality, and after availability (with a calendar).

I first try with a simple search form solution, but I think it's not the best solution, so I try with Justin Weiss solution but it didn't work, so I try to put my own filters in my user model but it's unsuccessfully :

model :

include Filterable

def self.apply_filters(params)
user = self
user = user_by_mother_tongue(mother_tongue: params[:mother_tongue]) if params[:mother_tongue].present?
user = user_by_locality(locality: params[:locality]) if params[:locality].present?
user
end

Being blocked, so I decided to prioprise on the filters mother_tongue and locality and keep filter calendar for later, however I can not find a way out ...

my users controller :

before :

def index
 @users = User.where(activated: true).paginate(page: params[:page])
end

after :

  def index
   @users = User.filter(params.slice(:mother_tongue, :locality))
  end

index.html.erb :

<% provide(:title, 'Liste des utilisateurs') %>
<h1>Liste des utilisateurs :</h1>

<%= form_tag(users_path, method: :get) do %>
 <%= label_tag :mother_tongue, "Langue :" %>
 <%= text_field_tag :mother_tongue, params[:mother_tongue] %>

 <%= label_tag :locality, "Ville :" %>
 <%= text_field_tag :locality, params[:locality] %>

 <%= submit_tag 'Search', name: nil %>
<% end %>

<table>
 <thead>
   <tr>
    <th></th>
   </tr>
 </thead>

 <tbody>
  <tr>
    <% for user in @users %>
      <div class='user'>
        <strong> <%= user.fname %> </strong>
      </div>
       <%= link_to 'Savoir plus', user_path(user) %>
    <% end %>
  </tr>       
</tbody>

models/concern/filterable.rb :

module Filterable
  extend ActiveSupport::Concern

  module ClassMethods
    def filter(filtering_params)
      results = self.where(nil)
        filtering_params.each do |key, value|
          results = results.public_send(key, value) if value.present?
        end
      results
    end
  end
end

Thanks in advance for your help !

Aucun commentaire:

Enregistrer un commentaire