How to compare DateTime in custom validations?
I'm trying to write a custom validation...people enter in a start and end time into a site and I'm trying to write a validation to check that the end comes after the start. I've tried to convert it to Unix time, but then I get a noMethodError. I would like to pass the symbols for the start time and end time into this method and then compare the two.
def validates_end_is_after_start(*attr_names)
start_hour = attr_names[0].to_i
end_hour = attr_names[1].to_i
The p开发者_高级运维roblem is that this ends up with a noMethodError for symbol. But that symbol points to a DateTime object (I think), how do I access that object? I think that there's something I don't understand about symbols in general.
You could use the validate
method which would have access to type-casted dates
class Something < ActiveRecord::Base
validate :valid_dates
def valid_dates
if start_time >= end_time
self.errors.add :start_time, ' has to be after end time'
end
end
end
Think of symbols just like strings, but with a lot less of functionality and behavior as objects. You should change your code to following:
def validates_end_is_after_start(*attr_names)
start_hour = self.send(attr_names[0].to_sym).to_i
end_hour = self.send(attr_names[1].to_sym).to_i
# ... more code here
end
You should also checkout the awesome gem validates_timeliness, which is made to handle validation of date, time and datetime.
Since Ruby on Rails 7.0 there is no need anymore for a custom validation in this case because Rails 7.0 supports validates_comparison_of
like this
validates :start_time, comparison: { less_than: :end_date }
精彩评论