Let you add scopes to active_record document for filters.
Add this line to your application's Gemfile:
gem 'active_record_filterable'
And then execute:
$ bundle
Or install it yourself as:
$ gem install active_record_filterable
class City < ActiveRecord::Base
include ActiveRecord::Filterable
filter_by(:name)
filter_by(:people, ->(value) { where(City.arel_table[:people].gt(value)) })
filter_by(:people_range, (lambda do |range_start, range_end|
where(people: range_start..range_end)
end))
end
City.create(name: 'city1', people: 100)
City.create(name: 'city2', people: 1000)
City.filtrate({name: 'city'}).count # => 2
City.filtrate({name: 'city1'}).count # => 1
City.filtrate({name: ''}).count # => 0
City.filtrate({people: 500}) # => 1
City.filtrate({invalid: 'x'}) # => 2 (is ignored)
You can specify selector operator:
- and (default operator)
- or
City.filtrate({name: 'city1', people: 1000}, 'and').count # => 0
City.filtrate({name: 'city1', people: 1000}, 'or').count # => 1
Searches with more than one param is also available:
City.filtrate(people_range: [500, 1000]).count # => 1
class CitiesController
def index
respond_with City.filtrate(filter_params)
end
private
def filter_params
params.slice(:name, :people)
end
end
Searches without considering accents are also supported.
filter_by_normalized :name
enables to do sth like:
City.filtrate(name_normalized: 'text with accents')
It also depends on which adapter you are using.
- Postgresql: It makes use of
unaccent
. You need to activate in your project. - Mysql, SqlServer: you only need to select an accent-insensitive collation. In cases where this is not possible you could even write:
filter_by :name, (lambda do |value| where("name LIKE ? COLLATE utf8_general_ci", "%#{value}%") end)
- Fork it ( http://github.com/nosolosoftware/active_record_filterable/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request