DateTime arithmetic in an ActiveRecord query (PostgreSQL)

时间秒杀一切 提交于 2020-01-10 04:08:15

问题


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.

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

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?


回答1:


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.




回答2:


You simply have to formulate that in PostgreSQL syntax inside your where clause.

For MySQL this would look similar to this using the datediff function:

User.where("DATEDIFF(created_at, birthdate) > (13 * 365)")

13*356 is there to represent 3 years in days since datediff returns difference in days.

I would then encapsulate that in a scope-like function like the following:

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

So you can call it:

User.age_difference(13).each do |user|
  puts user.inspect
end

I guess it's similar in Postgres.



来源:https://stackoverflow.com/questions/10301400/datetime-arithmetic-in-an-activerecord-query-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!