FilterForm
Build filter forms easily by using ransack
and simple_form
.
Installation
Add this line to your application's Gemfile:
gem 'filter_form'
And then execute:
$ bundle
Or install it yourself as:
$ gem install filter_form
Usage
In your contoller:
def index
@q = Person.search(params[:q])
@people = @q.result
end
In your view file:
<%= filter_form_for @q do |f| %>
<%= f.filter_input :married # boolean %>
<%= f.filter_input :name # string %>
<%= f.filter_input :age # integer %>
<%= f.filter_input :birthday # date %>
<%= f.filter_input :city # belongs_to %>
<%= f.filter_input :parents # has_many %>
<%= f.filter_input :amount # money %>
<%= f.filter_input :gender, as: :check_boxes, collection: [[:male, 'Male'], [:female, 'Female']] # checkboxes %>
<%= f.button :submit %>
<% end %>
Available types
Mapping | Database Column Type | Default predicate | Generated HTML Element |
---|---|---|---|
boolean |
boolean |
true |
input[type="checkbox"] |
string |
string |
cont |
input[type="text"] |
text |
text |
cont |
input[type="text"] |
integer |
integer |
eq |
input[type="number"] |
float |
float |
eq |
input[type="number"] |
decimal |
decimal |
eq |
input[type="number"] |
date |
date |
eq |
input[type="text"] |
datetime |
datetime |
eq |
input[type="text"] |
select |
belongs_to /has_many /has_and_belongs_to_many associations |
eq |
select |
money |
monetized attribute | eq |
input[type="number"] |
check_boxes |
`any' | in |
input[type=checkbox] |
radio_buttons |
`any' | eq |
input[type=radio] |
Customization
Custom predicate
<%= filter_form_for @q do |f| %>
<%= f.filter_input :year, as: :select, collection: (2000..2013).to_a, predicate: :not_eq %>
<%= f.button :submit %>
<% end %>
Predicate selector
You can show predicate selector:
<%= filter_form_for @q do |f| %>
<%= f.filter_input :id, predicate_selector: [['=', 'eq'], ['>', 'gt'], ['<', 'lt']] %>
<%= f.button :submit %>
<% end %>
Money
To filter by monetized attribute please add to your controller:
class ApplicationController < ActionController::Base
include FilterForm::MoneyConverter
...
end
Select2
You can wrap your select in select2
:
<%= filter_form_for @q do |f| %>
<%= f.filter_input :title, as: :select, in: :select2 %>
<%= f.button :submit %>
<% end %>
Assets
If you want to use predicate selector, jQuery Datepicker for date
and datetime
automatically or Select2, add to your application.js file:
//= require jquery
//= require jquery.ui.datepicker
//= require select2
//= require filter_form
And application.css:
*= require jquery.ui.datepicker
*= require select2
*= require filter_form
Other sources
For more information about predicates visit ransack.
If you want to customize your form visit simple_form.
Contributing
- Fork it
- 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