Last active
January 30, 2025 13:06
-
Star
(278)
You must be signed in to star a gist -
Fork
(34)
You must be signed in to fork a gist
-
-
Save justinweiss/9065666 to your computer and use it in GitHub Desktop.
Filterable
This file contains 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
# Call scopes directly from your URL params: | |
# | |
# @products = Product.filter(params.slice(:status, :location, :starts_with)) | |
module Filterable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
# Call the class methods with names based on the keys in <tt>filtering_params</tt> | |
# with their associated values. For example, "{ status: 'delayed' }" would call | |
# `filter_by_status('delayed')`. Most useful for calling named scopes from | |
# URL params. Make sure you don't pass stuff directly from the web without | |
# whitelisting only the params you care about first! | |
def filter(filtering_params) | |
results = self.where(nil) # create an anonymous scope | |
filtering_params.each do |key, value| | |
results = results.public_send("filter_by_#{key}", value) if value.present? | |
end | |
results | |
end | |
end | |
end |
Hi All,
I would like to know how can I implement this Filterable module in my views. I ma new to Rails..
I have table with 40 plus columns but I would like to apply filters for few columns like :status, :name etc
I should be able to dropdown, select the required status and apply filters
thanks inadvance for your support..
I had some issues using this with pundit gem policy scopes. I suggest renaming filter to filter_by. Has the benefit of consistent naming with scopes.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My very own version:
without the explicit anonymous scope and redundant
self
's