DateTime arithmetic in an ActiveRecord query (PostgreSQL)

后端 未结 2 1946
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 16:40

I have two datetime columns in a User/users table: created_at and birthdate. I\'d like to find users whose b

相关标签:
2条回答
  • 2020-12-19 17:44

    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.

    0 讨论(0)
  • 2020-12-19 17:44

    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.

    0 讨论(0)
提交回复
热议问题