Question

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)
Was it helpful?

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top