简体   繁体   中英

Filterrific on Rails 5

Does anyone have experience with Rails 5 and Filterrific?

I was following the documentation - http://filterrific.clearcove.ca/ - did not work, although I did not receive any errors either. It does not update the results and debugging it shows that it reads all entries without applying filter values.

I was also downloading the demo application to adopt it - https://github.com/jhund/filterrific_demo - Did not work either - same results.

Rails version: Rails 5.0.0 Version filterrific: filterrific (2.0.5) Ruby version: ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15]

Tables

contacts: (belongs_to contact_type)

title content content_type_id

contact_types: (has_many contacts)

name

Contact Model

class Contact < ApplicationRecord

  filterrific(
      default_filter_params: { :sorted_by => 'created_at_desc' },
      :available_filters => %w[
          sorted_by
          search_query
          with_contact_type_id
          with_created_at_gte
      ]
  )

  self.per_page = 10

  belongs_to :contact_type
  belongs_to :user

  validates :contact_type_id, presence: true
  validates :content, presence: true

  scope :search_query, lambda { |query|
    return nil  if query.blank?

    terms = query.downcase.split(/\s+/)

    terms = terms.map { |e|
      (e.gsub('*', '%') + '%').gsub(/%+/, '%')
    }
    num_or_conditions = 2
    where(
        terms.map {
          or_clauses = [
              "LOWER(contacts.title) LIKE ?",
              "LOWER(contacts.content) LIKE ?"
          ].join(' OR ')
          "(#{ or_clauses })"
        }.join(' AND '),
        *terms.map { |e| [e] * num_or_conditions }.flatten
    )
  }
  scope :sorted_by, lambda { |sort_option|
    direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'

    case sort_option.to_s
      when /^created_at_/
        order("contacts.created_at #{ direction }")
      when /^contact_type_name_/
        order("LOWER(contact_types.name) #{ direction }").includes(:contact_type)
      else
        raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")
    end
  }
  scope :with_contact_type_id, lambda { |contact_type_ids|
    where(:contact_type_id => [*contact_type_ids])
  }
  scope :with_created_at_gte, lambda { |ref_date|
    where('contacts.created_at >= ?', ref_date)
  }

  delegate :name, :to => :contact_type, :prefix => true

  def self.options_for_sorted_by
    [
        ['Date received (newest first)', 'created_at_desc'],
        ['Date received (oldest first)', 'created_at_asc'],
        ['Subject (a-z)', 'contact_type_name_asc']
    ]
  end

end

ContactType Model

class ContactType < ApplicationRecord
  translates :name

  has_many :contacts, :dependent => :nullify

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

Contact Controller - Index

class ContactsController < ApplicationController
  before_action :set_contact, only: [:show, :edit, :update, :destroy]
  layout 'sidenav'
  include Pundit
  # helper_method :sort_column, :sort_direction

  # GET /contacts
  # GET /contacts.json
  def index
    @filterrific = initialize_filterrific(
        Contact,
        params[:filterrific],
        select_options: {
            sorted_by: Contact.options_for_sorted_by,
            with_contact_type_id: ContactType.options_for_select
        },
        persistence_id: 'shared_key',
        default_filter_params: {},
        available_filters: [],
    ) or return

    @contacts = @filterrific.find.paginate(page: params[:page], per_page: 25)

    authorize @contacts

    # Respond to html for initial page load and to js for AJAX filter updates.
    respond_to do |format|
      format.html
      format.js
    end

  rescue ActiveRecord::RecordNotFound => e
    # There is an issue with the persisted param_set. Reset it.
    puts "Had to reset filterrific params: #{ e.message }"
    redirect_to(reset_filterrific_url(format: :html)) and return
  end

  ...

end

Views

index.html.haml

      = form_for_filterrific @filterrific do |f|
        %div{:style => "width: 25%;float: left;"}
          Search
          = f.text_field(:search_query,
              class: 'filterrific-periodically-observed form-control')
        %div{:style => "width: 25%;float: left;"}
          Subject
          #{f.select( :with_contact_type_id, @filterrific.select_options[:with_contact_type_id], { include_blank: '- Any -' }, :class => "form-control" )}
        %div{:style => "width: 25%;float: left;"}
          Sent after
          #{f.text_field(:with_created_at_gte, :"data-provide" => 'datepicker', :class => "form-control")}
        %div{:style => "width: 25%;float: left;"}
          Sorted by
          #{f.select(:sorted_by, @filterrific.select_options[:sorted_by], {}, :class => "form-control")}
        %div
          = link_to('Reset filters', reset_filterrific_url)
        = render_filterrific_spinner
      #results
        = render(partial: 'contacts/list_contacts', locals: { contacts: @contacts })

_list_contacts.html.haml

%table.table
  %thead
    %tr
      %th= "Subject"
      /= sortable "contact_type_id", "Subject", params[:filter]
      %th Message
      %th= "Sender"
      /= sortable "user_id", "Sender", params[:filter]
      %th= "Status"
      %th= "Created"
      /= sortable "created_at", "Created", params[:filter]
      %th
  %tbody
    - contacts.each do |contact|
      %tr
      %td
        - unless contact.contact_type.nil?
          = contact.contact_type.name
      %td= truncate(contact.content, length: 100)
      %td= contact.user.email
      %td= check_status(contact.closed)
      %td= contact.created_at.strftime("%B %d, %Y")
      %td.actions
        = link_to fa_icon_tag("eye-open"), contact, rel: 'tooltip', title: 'Show'
        = link_to fa_icon_tag("pencil"), edit_contact_path(contact), rel: 'tooltip', title: 'Edit'
        = link_to fa_icon_tag("trash"), contact, rel: 'tooltip', title: 'Delete', data: { confirm: 'Are you sure?' }, method: :delete

index.js.erb

<% js = escape_javascript(
  render(
    :partial => 'contacts/list_contacts',
    :locals => { contacts: @contacts }
  )
) %>
$("#results").html("<%= js %>");

Console output

Started GET "/en/dashboard/admin/support/contacts?utf8=%E2%9C%93&filterrific%5Bsearch_query%5D=Hello&filterrific%5Bwith_contact_type_id%5D=1&filterrific%5Bwith_created_at_gte%5D=&filterrific%5Bsorted_by%5D=created_at_desc&_=1475267744268" for ::1 at 2016-09-30 21:35:51 +0100
DEBUG: Chewy strategies stack: [2] <- atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17
Processing by ContactsController#index as JS
  Parameters: {"utf8"=>"✓", "filterrific"=>{"search_query"=>"Hello", "with_contact_type_id"=>"1", "with_created_at_gte"=>"", "sorted_by"=>"created_at_desc"}, "_"=>"1475267744268", "locale"=>"en"}
  User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 4], ["LIMIT", 1]]
  ContactType Load (0.6ms)  SELECT "contact_types".* FROM "contact_types" ORDER BY LOWER(name)
  Rendering contacts/index.js.erb
  Contact Load (0.6ms)  SELECT  "contacts".* FROM "contacts" ORDER BY contacts.created_at desc LIMIT $1 OFFSET $2  [["LIMIT", 25], ["OFFSET", 0]]
  ContactType Load (0.6ms)  SELECT  "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 9], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 8], ["LIMIT", 1]]
  Rendered contacts/_list_contacts.html.haml (27.0ms)
  Rendered contacts/index.js.erb (31.7ms)
Completed 200 OK in 150ms (Views: 101.3ms | ActiveRecord: 4.2ms)

I Followed the documentation and I had to comment out line

    #available_filters: [],

in controller file, and now it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM