Reputation: 9075
How to validate start date on update that it should not be previous date than previously saved date. eg:- like I have created record with start date as 07/11/2013, on update it should not before the 07/11/2013.
in view:
f.input :start_date, as: :datepicker
f.input :end_date, as: :datepicker
model:
validates :start_date, allow_nil: true, date: { after: Date.today - 1, message: 'must be today or after today' }, on: :create
validates :end_date, allow_nil: true, date: { after: :start_date, message: 'must be after start date' }
Thanks.
Upvotes: 0
Views: 205
Reputation: 774
You can add attr_accessor :previous_start_date(dont forget also about attr_accessible) plus add hidden field on form. This field must have value equal to start_date from DB. Then you can use after :previous_start_date. Note: value previous_start_date must be set from DB, maybe better to do it in model in getter method or set in before_validation callback.
Upvotes: 1
Reputation: 1307
I can't test it right now but I think it might work:
validate :previous_start_date
def previous_start_date
old_start_date = Model.find(self.id).start_date
if(old_start_date > self.start_date)
self.errors.add(:start_date, "Can't be previous than the initial date")
end
end
At the moment of the validation, the object hasn't been saved yet, so, I believe that retrieving the object from the database will give you the previous value. With the value in hand you can compare with the current start_date and then add your custom error.
I hope it helps.
Upvotes: 1