Active Query: object date within the next 30 days.
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) }
end
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.