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

2

5

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)
Catlaina answered 20/8, 2012 at 18:45 Comment(2)
What is the type of attribute :birthday? Where are you stuck?Shererd
:birthday is a Date. I found the solution right now. I'm writing to post here.Catlaina
C
6

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.

Catlaina answered 20/8, 2012 at 21:4 Comment(2)
In the latest ActiveAdmin, MetaSearch has been replaced with Ransack so you'll need to use ransacker instead of search_method. Here's an example.Fariss
@onemanarmy can you kindly show how to implement this with ransacker? Thanks!Suspender
C
2

Solution for recent versions of Active Admin:

#app/admin/employees.rb
filter :month, :as => :select, :collection => (1..12)

#app/models/employee.rb
scope :month_eq, ->(month) { where('MONTH(birthday) = ?', month.to_i) } # for MySQL

def self.ransackable_scopes(_auth_object = nil)
  [:month_eq]
end
Copepod answered 29/7, 2016 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.