Home > OS >  How to add a datefield attribute with integer attribute using ActiveRecord
How to add a datefield attribute with integer attribute using ActiveRecord

Time:11-30

I have a rails model with two attributes, one is a datetime field and the other is an integer. I'm trying to add a scope using both these fields & it gives me incorrect results.

ModelName.where("model.created_at   model.hours > ?", Time.now)

Model.created_at is of class ActiveSupport::TimeWithZone and Model.hours is Integer.

Sample data

created_at: Mon, 28 Nov 2022 10:16:39.095488000 UTC  00:00,
hours: 5

CodePudding user response:

If you're using PostgreSQL, I think you can use something like:

ModelName.where("created_at   interval '1 hour' * hours > ?", Time.now)

For MySQL:

ModelName.where("DATE_ADD(created_at, INTERVAL hours hour) > ?", Time.now)
  • Related