活动支架:在带有时间戳的列上进行字段搜索

Active Scaffold: field search on column with timestamp

我根据 FieldSearch-API-Documentation 在我的控制器中启用了字段搜索功能。

我已经启用了如下两列的字段搜索

class FooController < ApplicationController
   active_scaffold 'foo' do |config|
     # allowed actions
     config.actions = [:create, :update, :delete, :field_search, :list, :nested, :show]

     # columns
     config.columns = [:date, :created_at]

     # searchable columns
     config.field_search.columns = :date, :created_at
     config.list.always_show_search = true

     # list columns
     config.list.columns = [:date, :created_at]

     [...]

   end
end

日期列是日期类型,created_at列是 postgresql 数据库中的时间戳类型。

使用上面的配置参数,我成功地在活动脚手架呈现的视图上获得了一个搜索表单。在搜索表单上有一个带有运算符(例如 BETWEEN)的下拉列表和两个用于选择范围的输入控件。

现在的问题是,按日期搜索工作正常,按 created_at 搜索不起作用。

经过详尽的研究后,我发现了一个 hint,它描述了活动脚手架默认使用在 ./config/locales/en.yml 下配置的日期时间格式,并在我的案例中显示如下。

en:
   time:
       formats:
           default: "%Y%m%d%H%M%S"

显然,输入格式如何很重要。按 created_at 搜索的搜索输入例如:从 20180101000000 到 20181231000000.

Column-API-Documentation 我发现了以下内容:

options[:format] can be set for: date and time columns, and it will be used as the format argument of I18n.localize to format them.

我不明白我必须在控制器中的选项参数中定义什么样的值?

config.columns[:created_at].options[:format] = ???

刚刚在写问题的时候找到了答案:-)

如果我在 ./config/locales/en.yml 中定义一个新条目,例如时间戳如下

en:
    time:
        formats:
             timestamp: "%Y%m%d%H%M"

并在我的控制器中执行以下操作

config.columns[:created_at].options[:format] = "timestamp"

然后我可以通过输入 201801010000 和 201812310000 成功地通过 created_at 进行搜索。