mardi 27 septembre 2016

using filterrific gem to filter table by column

I have a simple user table on which I want to filter by two attributes. The user attributes consists of Id,name,age,status,location and I want to allow filter by both age and status. I followed filterrific instructions but got lost and messed up.

In my model user.rb I added

filterrific :available_filters => %w[
                with_age
                with_status
              ]

scope :with_age, lambda { |ageNumber|
  where(:age => [*ageNumber])
}
scope :with_status, lambda { |status|
  where(:status => [*status])
}

then in my controller I added

def index
    @filterrific = initialize_filterrific(
      User,
      params[:filterrific],
      select_options: {
        with_age: User.options_for_select,
        with_status: User.option_for_select2,
      },
      persistence_id: 'shared_key',
      default_filter_params: {},
      available_filters: [],
    ) or return

    @users = @filterrific.find.page(params[:page])
  end

def self.options_for_select
  order('LOWER(age)').map { |e| [e.age, e.age] }
end

def self.options_for_select2
  order('LOWER(status)').map { |e| [e.status, e.status] }
end

In my view

<%= form_for_filterrific @filterrific do |f| %>

  <div>
    status
    <%= f.select(
      :with_status
      @filterrific.select_options[:with_status],
      { include_blank: '- Any -' }
    ) %>
  </div>
  <div>
    age
    <%= f.select(
      :with_age
      @filterrific.select_options[:with_age],
      { include_blank: '- Any -' }
    ) %>
  </div>

<% end %>

Aucun commentaire:

Enregistrer un commentaire