简体   繁体   English

Rails:在数据库中搜索部分日期时间

[英]Rails: Search DB for part of datetime

I have a problem.我有个问题。 In my application I have a list with data.在我的应用程序中,我有一个包含数据的列表。 This data includes a datetime_utc column.此数据包括 datetime_utc 列。 There is also a searchbar which allows the user to search for datetime strings, but the searchbar is now requiring precise inputs, so for example these inputs return a result:还有一个允许用户搜索日期时间字符串的搜索栏,但搜索栏现在需要精确输入,因此例如这些输入返回结果:

2023-01-01 02:00:00
2023-01-01 02:00
2023-01-01 02

As long as the input string starts with a valid datetime format.只要输入字符串以有效的日期时间格式开头。 What I want is for example to look for only a given time like:例如,我想要的是仅查找给定时间,例如:

02:00

This should return all data with the time 02:00:00 as datetime_utc value.这应该返回时间为02:00:00的所有数据作为datetime_utc值。 Right now this is my code:现在这是我的代码:

data = data.where(datetime_utc: "#{params[:search]}") if params[:search] && params[:search] != ''

And I have tried things like this:我试过这样的事情:

data = data.where("to_char(datetime_utc, 'YYYY-MM-DD HH24:MI:SS') LIKE ?": "%#{params[:search]}%") if params[:search] && params[:search] != ''

But this gives me the error:但这给了我错误:

PG::UndefinedColumn: ERROR:  column candlesticks.to_char(datetime_utc, 'YYYY-MM-DD HH24:MI:SS') LIKE ? does not exist

So I understand that Postgres formats the given input string to a datetime format first and I it can't do that, it crashes.所以我知道 Postgres 首先将给定的输入字符串格式化为日期时间格式,但我不能这样做,它崩溃了。

There must be a way to still get this to work right?一定有办法让它正常工作吗?

Rails is considering "to_char(datetime_utc, 'YYYY-MM-DD HH24:MI:SS') LIKE?" Rails 正在考虑"to_char(datetime_utc, 'YYYY-MM-DD HH24:MI:SS') LIKE?" as column name because of the incorrect format used作为列名,因为使用的格式不正确

You need to change your query to (Notice the : is replaced with , )您需要将查询更改为(注意:被替换为,

data = data.where("to_char(datetime_utc, 'YYYY-MM-DD HH24:MI:SS') LIKE ?", "%#{params[:search]}%") if params[:search] && params[:search] != ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM