【问题标题】:Active Admin custom filter. Filter date by day | month | year of a Date attribute活动管理员自定义过滤器。按天过滤日期 |月 | Date 属性的年份
【发布时间】:2012-08-16 02:44:19
【问题描述】:

我有一个带有 :birthday 属性的模型,我想按表单中指定的月份过滤掉那些日期(ActiveAdmin 的 DSL :select)。

这是一个仅提取生日月份的简单范围示例。也许可以帮助:

scope :birthday_month, where('extract(month from birthday) = ?', Date.today.month)

【问题讨论】:

  • 属性类型:生日是什么?你被困在哪里了?
  • :生日是一个日期。我现在找到了解决方案。我写信在这里发帖。

标签: ruby-on-rails activeadmin meta-search


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是一个解决方案:

    在我的 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 使其可用(MetaSearch 也是)。

    注意:
    如果您不使用 sqlite,也许您会希望使用where('extract(month from birthday) = ?', month.to_i)

    【讨论】:

    • 谢谢!非常感谢!
    • 在最新的 ActiveAdmin 中,MetaSearch 已被 Ransack 取代,因此您需要使用 ransacker 而不是 search_method。这是example
    • @onemanarmy 你能告诉我如何用 ransacker 实现这个吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多