Reputation: 3272
I have a form_for which give me two datetime format (start and end dates). My goal is to check that end_date > start_date.
In my model I don't know how to do that, here is what I did so far (not working) :
class XXX < ActiveRecord::Base
before_create :check_dates
private
def check_dates
if self.end_date > self.start_date //I don't know how to do it
end
end
Error :
syntax error, unexpected end-of-input, expecting keyword_end
Thanks
Upvotes: 2
Views: 3243
Reputation: 9173
You are getting this error because inside your callback you only have a condition, you didn't specify what to do when this condition evaluates to true also you didn't close your if statement hence a syntax error. Although your callback will also do the same thing but in your case i think it'll be better if you use a validation instead
class XXX < ActiveRecord::Base
validate :check_dates
def check_dates
errors.add(:base, "end date should be greater than start") if self.end_date > self.start_date //I don't know how to do it
end
end
Upvotes: 4
Reputation: 2300
Mandeep's answer is comprehensive and covers what you want. I just want to add if you are looking to use this validator in other models you can create a validator model:
class MyValidator < ActiveModel::Validator
def validate(record)
if record.end_date > record.start_date
record.errors[:base] << 'End date should be greater that start date!'
end
end
end
class XXX < ActiveRecord:Base
include ActiveModel::Validations
validates_with MyValidator
end
The code is from rubyonrails.org: http://edgeguides.rubyonrails.org/active_record_validations.html
Upvotes: 2