DateTime arithmetic in an ActiveRecord query (PostgreSQL)

后端 未结 2 1950
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题