Created
June 14, 2019 03:05
-
-
Save syafiqfaiz/f1c0a4338a2147241baba7a45157d3ef to your computer and use it in GitHub Desktop.
A module to make a clean and simple filtering
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
module Filterable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def filter(filtering_params) | |
results = self.where(nil) | |
filtering_params.each do |key, value| | |
results = results.public_send(key, value) if value.present? | |
end | |
results | |
end | |
end | |
end | |
. | |
. | |
. | |
class User < ApplicationRecord | |
include Filterable | |
scope :email_q, -> (email) { where("LOWER(email) like ?", "%#{email.downcase}%")} | |
scope :name_q, -> (name) { where("LOWER(name) like ?", "%#{name.downcase}%")} | |
end | |
. | |
. | |
. | |
def index | |
@users = User.filter(filtering_params) | |
end | |
def filtering_params | |
params.slice(:email_q, :name_q) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment