Rails validator: Only add if occurred_at is after latest entry?
I have an Event
mo开发者_开发技巧del that stores tracking events from carriers (Shipped, Out for delivery, Delivered, etc etc).
We ping the carrier API's on a regular basis to get new status updates, but I only want to add new tracking "events" if their occurred_at
date/time is after the latest entry.
So if the last event we have occurred at "2011-08-19 06:44:00" then only events that have a later date/time should be added.
I'm trying to do something like this, but in a validator:
last_event = Event.find_by_number_id(id, :order => 'occurred_at DESC')
if !last_event || (new_event.occurred_at > last_event.occurred_at)
new_event.save
end
I'm running Rails 3.0.9.
I know it's not a real validator, but you could use something like:
validate do
last_event = Event.find_by_number_id(id, :order => 'occurred_at DESC')
errors.add(:occured_at, :invalid) if !last_event || (new_event.occurred_at > last_event.occurred_at)
end
You can create your custom validation method or use default validate
method. Just put your code into validation method and return errors.add(:some_error, "some message")
when it fails criteria. Take a look at this guide: Rails validation
精彩评论