日期时间算术一个ActiveRecord查询

日期时间算术一个ActiveRecord查询

本文介绍了日期时间算术一个ActiveRecord查询(PostgreSQL系统)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户两个日期时间 / 用户表: created_at 生日。我想找到用户的出生日期是创建日期不到13年。

I have two datetime columns in a User/users table: created_at and birthdate. I'd like to find users whose birthdate is less than 13 years before their creation date.

等效Rails的如果声明将是((created_at - 出生日期)< 13.years)

The equivalent Rails if statement would be ((created_at - birthdate) < 13.years)

我如何转换成一个ActiveRecord的查询(一个会工作在PostgreSQL的)?这甚至可能,否则我将不得不手动遍历所有记录?

How do I translate this to an ActiveRecord query (one that'll work on PostgreSQL)? Is this even possible, or will I have to iterate over all records manually?

推荐答案

要做到这一点最简单的方法是使用interval,那么它是pretty的多的Rails的版本直接音译:

The easiest way to do this is to use an interval, then it is pretty much a straight transliteration of the Rails version:

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

两个时间戳(或时间戳和日期)之间的差异是一个区间,所以你只需要在右边你比较合适的值。

The difference between two timestamps (or a timestamp and a date) is an interval so you just need the appropriate value on the right side of your comparison.

这篇关于日期时间算术一个ActiveRecord查询(PostgreSQL系统)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:58