Ransack 搜索日期作为字符串

Ransack Search Date as a String

我在我的应用程序中使用搜查 gem 作为搜索机制。我面临的问题是,在我的模型中,我不小心将 "date" 列创建为字符串字段,因此日期搜索不起作用,我无法根据日期进行比较。由于该列的数据类型是字符串,所以 ransack 没有带来合适的结果。

@q = MyModel.order(id: :desc).ransack(params[:q])
@records = @q.result(distinct: true)

我在那个 Table 中有大量实时数据,我不想通过编写迁移来冒险。任何帮助将不胜感激

有一个简单的 hack,您可以使用它并在数据库级别将字符串转换为数据。 您需要添加以下方法的模型。

ransacker :name_of_your_column_to_d do
    Arel.sql("cda")
end

然后在您的控制器中进行以下更改。

# You can use DESC id if you want to change order. 
@q = YourModel.ransack({s: "id DESC"}.merge(params[:q] || {}))

@q.result(distinct: true).select("*, to_date(\"your_model_table_name\".\"your_date_column_name\", 'MM/DD/YYYY') as cda, your_model_table_name.id")

如果您需要进一步的帮助,请告诉我。