Based on Justin Weiss' blog post Search and Filter Rails Models Without Bloating Your Controller, Filterable enables you to replace MyModel.find.long.string.of.conditions with MyModel.filter(list_of_scopes).
Add this line to your application's Gemfile:
gem 'filterable'
And then execute:
$ bundle
Or install it yourself as:
$ gem install filterable
- In your model, consider the attributes you want to match.
- Create scopes that match appropriately.
scope :name, ->(p) { where(name: p) }
scope :category, ->(p) { where(category: p) }
- In your view, make sure these params will be sent on submit.
- In your controller, use ModelName.filter(params.slice(:name, :category))
- Add methods to create simple scopes
- Keep a list of auto-created scopes to use as the default list if no params are passed to the #filter method
- Add a method to refer to existing scopes, (add them to the default list)
- Fork it ( http://github.com/neophiliac/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