Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 894
Theo B Avatar asked Aug 20 '12 18:08

Theo B


1 Answers

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.

like image 130
Theo B Avatar answered Sep 21 '22 14:09

Theo B