gpt4 book ai didi

ruby-on-rails - 如何在 pg/Rails 中选择涵盖今天和月份的行

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:35 25 4
gpt4 key购买 nike

所以我有这个名为 SeasonRate 的表

create_table "season_rates", force: :cascade do |t|
t.string "title"
t.datetime "from_date"
t.datetime "to_date"
t.float "rate"
t.integer "property_type_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["property_type_id"], name: "index_season_rates_on_property_type_id", using: :btree
end

我希望能够找到今天的日期在 from_dateto_date 之间的行,忽略年份。到目前为止,使用 this我已经能够写出这段代码了

def todays_rate(apartment)
property_type = apartment.property_type_id
@rate = SeasonRate.where(property_type_id: property_type)
@todays_rate = @rate.where("extract (DOY FROM TIMESTAMP from_date) <= extract (DOY FROM TIMESTAMP ?) AND extract (DOY FROM TIMESTAMP to_date) >= extract (DOY FROM TIMESTAMP ?)",Date.today, Date.today)
end

但它给了我错误的说法

PG::SyntaxError: ERROR: syntax error at or near "from_date" LINE 1: ...ty_type_id" = $1 AND (extract (DOY FROM TIMESTAMP from_date)... ^ : SELECT "season_rates".* FROM "season_rates" WHERE "season_rates"."property_type_id" = $1 AND (extract (DOY FROM TIMESTAMP from_date) <= extract (DOY FROM TIMESTAMP '2017-08-04') AND extract (DOY FROM TIMESTAMP to_date) >= extract (DOY FROM TIMESTAMP '2017-08-04'))

我已经搜索了很多这个问题,但找不到任何解决方案。请帮助我我在这里做错了什么,或者如果您有更好的解决方案来解决这个问题,那就太好了。非常感谢。

最佳答案

我可能是错的,但看起来添加 TIMESTAMP 是告诉 Postgres 将字符串转换为时间戳,然后你不是给它一个字符串,而是给它一个列名称,因此语法错误:

select EXTRACT(DOY FROM TIMESTAMP created_at), created_at from users;
ERROR: syntax error at or near "created_at"
LINE 1: select EXTRACT(DOY FROM TIMESTAMP created_at), created_at fr...

但你可以只给它列名而不是要转换的字符串,它似乎工作正常

select EXTRACT(DOY FROM created_at), created_at from users;
date_part | created_at
-----------+----------------------------
190 | 2017-07-09 21:07:41.746157

关于ruby-on-rails - 如何在 pg/Rails 中选择涵盖今天和月份的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45497749/

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