-
-
Save MSeneadza/6f78e9d1f7984d9bded7 to your computer and use it in GitHub Desktop.
Just a refactoring of code from: http://www.justinweiss.com/blog/2014/02/17/search-and-filter-rails-models-without-bloating-your-controller/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Filterable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def filter(filtering_params) | |
filtering_params.reduce(self) do |relation, (scope_name, value)| | |
relation.public_send(scope_name, value) if value.present? | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
and from a comment on the original:
This will return nil if one or more of the parameters are passed with a blank value, which means you won't be able to chain any methods after .filter in the controller, such as .page(params[:page]) if you were using a pagination gem like Kaminari, for example. The filter method should always be returning a chainable relation, in this case via .all if none of the filters are set.
Here's what it should look like: