[英]Active Admin custom filter. Filter date by day | month | year of a Date attribute
我有一個帶有:birthday屬性的Model,我希望按表單中指定的月份過濾掉這些日期(ActiveAdmin的DSL:select)。
這是僅提取生日日期的簡單范圍的示例。 也許可以幫助:
scope :birthday_month, where('extract(month from birthday) = ?', Date.today.month)
這是一個解決方案:
在我的Active Admin資源(app / admin / employees.rb)上,我放了:
filter :month, :as => :select, :collection => (1..12)
在我的模型(app / models / employee.rb)上:
scope :month_eq, lambda{ |month| where("strftime('%m', birthday) + 0 = ?", month.to_i) }
search_methods :month_eq
這種方法定義'_eq'范圍方法(MetaSearch),並通過search_methods :month_eq
( search_methods :month_eq
)將其轉換為可用范圍。
注意:
如果你沒有使用sqlite,也許你會希望使用where('extract(month from birthday) = ?', month.to_i)
。
最新版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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.