gpt4 book ai didi

ruby-on-rails - Ransack 搜索日期作为字符串

转载 作者:数据小太阳 更新时间:2023-10-29 08:11:22 27 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

然后在您的 Controller 中进行以下更改。

# 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")

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

关于ruby-on-rails - Ransack 搜索日期作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38823081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com