Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord查询(PostgreSQL)中的日期时间算法_Ruby On Rails_Postgresql_Ruby On Rails 3_Activerecord_Rails Activerecord - Fatal编程技术网

Ruby on rails ActiveRecord查询(PostgreSQL)中的日期时间算法

Ruby on rails ActiveRecord查询(PostgreSQL)中的日期时间算法,ruby-on-rails,postgresql,ruby-on-rails-3,activerecord,rails-activerecord,Ruby On Rails,Postgresql,Ruby On Rails 3,Activerecord,Rails Activerecord,我在用户/用户表中有两列日期时间列:创建于和出生日期。我想找到出生日期比创建日期早13年的用户 等价的Railsif语句将是((在出生日期创建)

我在
用户
/
用户
表中有两列
日期时间
列:
创建于
出生日期
。我想找到出生日期比创建日期早13年的用户

等价的Rails
if
语句将是
((在出生日期创建)<13年)


如何将其转换为ActiveRecord查询(可用于PostgreSQL)?这是可能的,还是我必须手动迭代所有记录?

您只需在where子句中用PostgreSQL语法来表述即可

对于MySQL,这将类似于使用以下函数:

User.where("DATEDIFF(created_at, birthdate) > (13 * 365)")
13*356表示datediff返回天数差后的3年天数

然后,我将其封装在类似作用域的函数中,如下所示:

class User < ActiveRecord::Model
  def self.age_difference(years)
    where("DATEDIFF(created_at, birthdate) > (? * 365)", years)
  end
end

我想这在Postgres中是类似的。

最简单的方法是使用,然后它几乎是Rails版本的直接音译:

User.where(%q{created_at - birthdate < interval '13 years'})
User.where(%q{created_at-birthdate

两个时间戳(或一个时间戳和一个日期)之间的差值是一个间隔,因此您只需在比较的右侧输入适当的值即可。

您遇到了闰年问题。生命对于闰年问题来说太短了:D。。我只是认为这不是什么大问题。撇开闰年不谈,人们普遍认为一年有365天,而不是356天不管怎样,谢谢你的回答。@LouieGeetoo:人们普遍认为两位数就足以容纳一年的时间……Louigeeto:Ups;)是的,当你有20件事要做,但却在stackoverflow上闲逛时,就会发生这种情况。这很有效。非常感谢。其他阅读本文的人请注意:
interval
在SQLite上不起作用。我不得不使用PostgreSQL登录到我的生产服务器进行测试。@Louiegetoo:你真的不应该在不同的堆栈上开发和部署,日期算法的一点语法差异将是你的最小问题。
User.where(%q{created_at - birthdate < interval '13 years'})