Rails ActiveRecord,其中datetime不起作用

问题描述 投票:0回答:1

我有一个模型has_one Schedule(from:datetime,from_a:datetime,to:datetime)。我想检索所有具有适合运行查询的日期时间的模型。

例如,我的模型m的时间表来自:太阳,2018年10月15日19:00:00 UTC +00:00,from_a:太阳,2018年10月14日19:20:00 UTC +00:00和:太阳,2018年10月14日20:00:00 UTC +00:00。如果当前时间是太阳,2018年10月14日19:14:00 UTC +00:00然后我只搜索从那时起我会得到m,但是如果当前时间是太阳,那么,2010年10月14日20:01:00 UTC +00:00我只搜索我什么也得不到。

这是我尝试过的代码:

scope :s, ->(time, type) { unscoped.joins(:schedule).where("\"schedule.#{type.to_s}\" < ? AND \"schedule.to\" > ?", time, time) }

当我打电话的范围将是Model.s(DateTime.now, :from)。问题是这段代码没有按预期工作,因为它没有给我正确的结果,也没有给我预期的结果。

UPDATE 这是Model.s(DateTime.now, :from)生成的查询

SELECT "models".* FROM "models" INNER JOIN "schedules" ON "schedules"."model_id" = "models"."id" WHERE ("schedules.from" < '2018-10-15 19:59:33.737073' AND "schedules.to" > '2018-10-15 19:59:33.737073')
ruby-on-rails database datetime activerecord scoping
1个回答
1
投票

你有几个问题,第一个隐藏其他问题:

  1. 单引号用于SQL中的字符串文字,因此'schedule.from''schedule.to'只是SQL中的字符串,而不是对schedule表中列的引用。
  2. schedule应该是schedules,因为Rails喜欢使用复数作为表名。
  3. tofrom是SQL和PostgreSQL中的keywords(您似乎正在使用它们),因此当您将它们用作列名时,它们必须被(双重)引用。

第一个是通过删除杂散的单引号来修复的。第二个是使用复数表名。第三个是双重引用违规标识符。结果将是这样的:

unscoped.joins(:schedule).where(%Q(schedules."#{type.to_s}" < ? and schedules."to" > ?), time, time)

也许:

unscoped.joins(:schedule).where(%Q(schedules."#{type.to_s}" < :time and schedules."to" > :time), time: time)
© www.soinside.com 2019 - 2024. All rights reserved.