【问题标题】:How to add a datefield attribute with integer attribute using ActiveRecord如何使用 ActiveRecord 添加具有整数属性的日期字段属性
【发布时间】:2022-12-09 07:32:47
【问题描述】:

我有一个具有两个属性的 Rails 模型,一个是日期时间字段,另一个是整数。我正在尝试使用这两个字段添加一个范围,但结果不正确。

ModelName.where("model.created_at + model.hours > ?", Time.now)

Model.created_at 属于 ActiveSupport::TimeWithZone 类,而 Model.hours 属于 Integer

样本数据

created_at: Mon, 28 Nov 2022 10:16:39.095488000 UTC +00:00,
hours: 5

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    如果你使用的是 PostgreSQL,我想你可以使用类似的东西:

    ModelName.where("created_at + interval '1 hour' * hours > ?", Time.now)
    

    对于 MySQL:

    ModelName.where("DATE_ADD(created_at, INTERVAL hours hour) > ?", Time.now)
    

    【讨论】:

    • 不是 Postgres。 MySQL:/
    • @PreethiKumar 使用 MySQL 解决方案更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多