Possible Enhancement method - User.where(updated_at: within(6.months))

Often times, doing a query involves time based methods: “All users updated within the last 6 months”, “All posts older than 1 year”, etc.

My proposal is for an ActiveRecord helper method that would allow those queries to be written in a way similar to:

Users.where(updated_at: within(6.months))

Posts.where(updated_at: older_than(1.year))

Obviously that syntax may have to change to work with ActiveRecord/Arel.

I have been a Rails developer for about 3 years, so I’m very comfortable with Rails and ActiveRecord, though I have never contributed before. I am open to any and all suggestions or comments. I looked and didn’t see any similar proposals in Github issues, though I may have missed something. If there is positive feedback on this, I would love to take a stab at it and let that be my first contribution back to Rails and, with that, if you have any advice on actual implementation considerations, I would love to hear those ideas, too!

Thanks,

Jacob

Nice suggestion but I think it should be changed to not be so oriented to time fields. Those are just simple comparison operations.

This seems equally readable to me while having the benefit of making sense with any ordered type:

User.where(updated_at: greater_than(6.months.ago)) Post.where(updated_at: less_than(1.year.ago))

The method call inside where looks non idiomatic to me. Much cleaner if you simply define scopes with:

Users.where(‘updated_at > ?’ 6.months.ago)

Hi Jacob,

that sounds cool and maybe easy enough for a first Rails contribution (which I also never did but would like to). Do you know GitHub - jeremyevans/sequel: Sequel: The Database Toolkit for Ruby ? With Sequel you can do stuff like

posts.where(:stamp => (Date.today - 14)..(Date.today - 7))

which seems quite intuitive. Maybe we can just port that.

Jakub

Jakub, ActiveRecords allows this kind of query too, no need to port it. I have plenty of queries like that:

Model.where(date: (Time.zone.today - 30.days)…Time.zone.today)

I believe that similar queries will also work.