0

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.

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
Rob Hughes
  • 876
  • 2
  • 13
  • 32
  • 1
    Remove the condition. Does the attribute update now? If so, the problem is in the condition. Therefore, you might want to inspect and see what the record's date and `Date.today` are returning and then make a new condition based on that. – Wes Foster Feb 03 '16 at 20:35
  • To my surprise the attribute doesn't update even without the condition... I am not sure why. – Rob Hughes Feb 03 '16 at 20:41

2 Answers2

2

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)
Sergiy Isaev
  • 61
  • 1
  • 6
1

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.

apod
  • 578
  • 5
  • 16