【问题标题】:Rails 3 diffence between current_date and created_at value not workingRails 3 current_date 和 created_at 值之间的差异不起作用
【发布时间】:2014-02-05 02:44:31
【问题描述】:

我正在对 Rails 中的时间函数进行一些研究,我正在尝试获取 2 个日期之间的差异并将结果乘以一个数字,最后检查是否小于另一个值。公式应该是这样的。

where("? - created_at * (amount * 1.2 / 30) < total", Time.now)

但这就是我得到的。

PG::UndefinedFunction: ERROR: operator does not exist: timestamp without time zone * numeric

提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

我真的不知道我做错了什么。

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 postgresql-9.1 datediff


    【解决方案1】:

    乘以日期没有意义,这就是您正在做的事情:

    regress=> SELECT (TIMESTAMP '2012-01-01 00:00:00') * 1.2;
    ERROR:  operator does not exist: timestamp without time zone * numeric
    LINE 1: SELECT (TIMESTAMP '2012-01-01 00:00:00') * 1.2;
                                                     ^
    HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
    

    我认为您打算差异相乘,在这种情况下,您需要使用括号,因为* 在运算符优先级上的绑定比- 更紧密。所以:

    (? - created_at) * (amount * 1.2 / 30)
    

    【讨论】:

    • 好吧,我按照你说的修改了我的代码,但错误仍然存​​在
    【解决方案2】:

    好吧,我使用了一个名为 age 的 postgres 函数,它接收两个日期,不过可以改进

    (((prestamos.monto * 1.2) / 30) * (extract(day from age(now(),prestamos.created_at))))
    

    【讨论】:

      【解决方案3】:

      您可能需要先将差异转换为浮点数(使用 .to_f)。

      有点像

      where("? - created_at.to_f * (amount * 1.2 / 30) &lt; total", Time.now.to_f)

      另外,由于它在抱怨时区,to_timestamp() 将返回一个带有时区的时间戳

      编辑: 要向您的应用添加时区,请将类似这样的内容添加到 config/application.rb

      中的模块代码中
      module YourApp
          class Application < Rails::Application
          config.time_zone = 'Cairo' #your timezone goes here
          config.active_record.default_timezone = :local
      end
      

      为查找时区名称的任务列表运行“rake -D time”。默认为 UTC。

      Time Zones on Wikipedia

      如果您的应用在 Heroku 上,那么神奇的命令会变成:

      heroku config:add TZ="America/Los_Angeles"

      【讨论】:

      • 好的,谢谢,我试试这个。顺便问一下,你知道如何将我的时区设置为波哥大/拉丁美洲吗?
      • 抱歉,这对您不起作用。要设置时区,您可以编辑您的 application.rb 文件。我将在我的答案中包含此内容以保留格式
      猜你喜欢
      • 1970-01-01
      • 2019-08-15
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多