Ask A Question


You’re not receiving notifications from this thread.

Active Query: object date within the next 30 days.

Matt asked in Rails

Hi there,

I'm fairly new to programming and rails. I was wondering if someone could help point me in the right direction here.

I've created a new date field in Active Record and I'm trying to iterate through my objects that are coming up within the next 30 days. Would something like this be appropriate, or how should I go about doing this?

@nodes.where('cutdate', 30.days.from_now)


Hey Matt,

You're almost right. You just need to find things between Date.current and 30.days.from_now so you don't query for the exact day 30 days out. That way you get everything between now and then.

@nodes.where('cutdate BETWEEN ? AND ?', Date.current, 30.days.from_now)

And you can make that a scope:

class Node < ApplicationRecord
  scope :upcoming, ->{ where('cutdate BETWEEN ? AND ?', Date.current, 30.days.from_now) }

Wow, thank you so much Chris!! That worked. :)

That's the first time I've used a scope and it seems so magical now! I need to go read up on using them more.


Yeah! Aren't they handy? It just makes your code so much more readable later on.

Also, another small pro-tip is you can do a scope with an argument like so:

scope :in_next_days, ->(amount) { where("cutdate BETWEEN ? AND ?", Date.current, amount.days.from_now) }

This would let you call Node.in_next_days(30) and pass in the length of time if you wanted the next 7 days or something different.


So handy!

Thank you for the pro-tip. That will be really nice to implement for my next widget.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.