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)
Theo B
  • 351
  • 1
  • 3
  • 12

2 Answers2

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.

Theo B
  • 351
  • 1
  • 3
  • 12
  • 5
    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](https://github.com/ernie/ransack/blob/master/spec/support/schema.rb#L18). – manafire Jul 12 '13 at 20:11
  • 3
    @onemanarmy can you kindly show how to implement this with ransacker? Thanks! – unpangloss Sep 17 '13 at 03:42
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
Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24