ruby-on-railsactiveadminmeta-search

Active Admin custom filter. Filter date by day | month | year of a Date attribute


I have a Model with :birthday attribute and I want to filter out those dates by month specified in the form (ActiveAdmin's DSL :select).

This is an example of simple scope that extract only the month of birthday's date. Maybe can help:

scope :birthday_month, where('extract(month from birthday) = ?', Date.today.month)

Solution

  • Here is a solution:

    On my Active Admin resource (app/admin/employees.rb) I put:

    filter :month, :as => :select, :collection => (1..12)
    

    And on my Model (app/models/employee.rb):

    scope :month_eq, lambda{ |month| where("strftime('%m', birthday) + 0 = ?", month.to_i) }
    
    search_methods :month_eq
    

    This approach define '_eq' scope method (MetaSearch) and turn it avaible through search_methods :month_eq (MetaSearch too).

    NOTE:
    If you aren't using sqlite, maybe you'll desire to use where('extract(month from birthday) = ?', month.to_i) instead.