Reputation: 906
I feel this is a very noob question but here goes.
I have a model (gig) with a datetime attribute (date), and an expired boolean attribute (expired).
I want the expired boolean to set to true when the datetime date passes todays date.
In Gig model:
def expired
if self.date.to_date > Date.today
self.update(:expired, true)
end
end
doesn't work. Neither does:
def expired
if self('date < ?', Date.today)
self.update_attribute(:expired, true)
end
end
I feel this should be very simple but I cant find much info on this.
Upvotes: 0
Views: 1159
Reputation: 568
It's relevant to know the purpose of the boolean. If your goal is to be able to create a property to use in where queries throughout your code (e.g., getting all expired gigs), then a scope might be a good way to go. Just add this code to your Gig model:
scope :expired, -> { where('date < ?', Time.current.beginning_of_day) }
You could then get all the expired gigs by writing:
Gig.expired
Then you don't need the expired boolean at all. If you use your current method approach, you'd have to use a background process to set expired booleans everyday. See http://guides.rubyonrails.org/active_record_querying.html#scopes for more information on using scopes.
Upvotes: 1
Reputation: 61
Create a rake task with and run in every day at 23:59 (or any time you want).
Gig.where('date < ?', Date.today).update_all(expired: true)
Upvotes: 2