Custom Filter Method
Overview
We can add a custom filter method to filter records based on specific criteria. This is useful when the default filtering options do not meet the requirements. The custom filter method can be defined using the filter_with
option.
Usage
The custom filter method is implemented using the filter
dsl_method with the filter_with
option. Below are the key elements and their usage:
Syntax
filter :filter_name, :filter_type, filter_with: :custom_filter_method
Example
1. For Search and Select:
Define the custom filter method in your model:
class YourModel < ApplicationRecord
scope :custom_filter_method, ->(value) { where('column_name LIKE ?', "%#{value}%") }
end
Use the custom filter method in your cm admin:
filter :filter_name, :search, filter_with: :custom_filter_method
filter :filter_name, :single_select, helper_method: :options_for_select, filter_with: :custom_filter_method
2. For Date and Range:
Define the custom filter method in your model:
class YourModel < ApplicationRecord
scope :custom_filter_method, ->(from, to) { where('column_name BETWEEN ? AND ?', from, to) }
end
Use the custom filter method in your cm admin:
filter :filter_name, :date, filter_with: :custom_filter_method