Filterrific Rails 5
Filterrific on Rails 5
有人使用过 Rails 5 和 Filterrific 吗?
我按照文档 - http://filterrific.clearcove.ca/ - 没有工作,虽然我也没有收到任何错误。它不更新结果并调试它显示它读取所有条目而不应用过滤器值。
我也在下载演示应用程序以采用它 - https://github.com/jhund/filterrific_demo - 也没有工作 - 结果相同。
Rails版本:Rails5.0.0
filterrific 版本:filterrific (2.0.5)
Ruby 版本:ruby 2.2.4p230(2015-12-16 修订版 53155)[x86_64-darwin15]
表
联系人:(belongs_to contact_type)
标题
内容
content_type_id
contact_types:(has_many 联系人)
姓名
联系模特
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 型号
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
联系控制器 - 索引
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
观看次数
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 %>");
控制台输出
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" = ORDER BY "users"."id" ASC LIMIT [["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 OFFSET [["LIMIT", 25], ["OFFSET", 0]]
ContactType Load (0.6ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["id", 9], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["id", 9], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["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)
我按照文档进行操作,但我不得不注释掉行
#available_filters: [],
在控制器文件中,现在可以使用了。
有人使用过 Rails 5 和 Filterrific 吗?
我按照文档 - http://filterrific.clearcove.ca/ - 没有工作,虽然我也没有收到任何错误。它不更新结果并调试它显示它读取所有条目而不应用过滤器值。
我也在下载演示应用程序以采用它 - https://github.com/jhund/filterrific_demo - 也没有工作 - 结果相同。
Rails版本:Rails5.0.0 filterrific 版本:filterrific (2.0.5) Ruby 版本:ruby 2.2.4p230(2015-12-16 修订版 53155)[x86_64-darwin15]
表
联系人:(belongs_to contact_type)
标题 内容 content_type_id
contact_types:(has_many 联系人)
姓名
联系模特
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 型号
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
联系控制器 - 索引
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
观看次数
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 %>");
控制台输出
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" = ORDER BY "users"."id" ASC LIMIT [["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 OFFSET [["LIMIT", 25], ["OFFSET", 0]]
ContactType Load (0.6ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["id", 9], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["id", 9], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "contact_types".* FROM "contact_types" WHERE "contact_types"."id" = LIMIT [["id", 2], ["LIMIT", 1]]
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = LIMIT [["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)
我按照文档进行操作,但我不得不注释掉行
#available_filters: [],
在控制器文件中,现在可以使用了。