Last active
September 4, 2015 20:24
-
-
Save noahhendrix/9119825 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 |
Ok, I found the answer here. Destructuring in Ruby is a quite interesting topic I've somehow missed out.
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:
filtering_params.reduce(self) do |relation, (scope_name, value)|
value.present? ? relation.public_send(scope_name, value) : relation.all
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Noah, what is the reason the
Enumerable#reduce
returnsnil
if the hash key and value are passed like this|relation, scope_name, value|
?