I am attempting to validate some dates in a Rails 4 application and it's not working.
I looked at lots of similar code samples, like this Same custom validation for several fields in Rails and this http://railscasts.com/episodes/211-validations-in-rails-3. (And others more complicated). I don't understand why my example doesn't work. Trying to find the problem, I've stripped out the actual validation code, and left a stub, because the validation doesn't seem to run and that would seem the base problem (or at least, the first problem).
Here's the code in the validator (which is in app/validators/custom_date_validator.rb
class CustomDateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
puts "Custom validator was called"
record.errors[attribute] << "Date Not Valid" unless false
end
end
Here's the code from the model:
class CaseInformation < ActiveRecord::Base
include ApplicationHelper
validates :started, :custom_date => true
The error message is:
argument out of range
Extracted source (around line #104):
respond_to do |format|
104 if ( @case_information.update_attributes(params[:case_information]) && @case_information.update_attributes(params[:law_guardians]) )
format.html { redirect_to @case_information, notice: 'Case information was successfully updated.' }
format.json { head :no_content }
The error is (I think) intentional, I put in a date of "1/123/2012", but the validator isn't catching it. Well, actually I stripped out all the validation code and have (I think) the validator writing to the log, as it doesn't seem the validator is even running, at least, there's nothing in the log that shows it ran.
I know that the validator code is being found because in the model, if I change the validation name even a bit I get an error that the validation can't be found.
Really stupid noob question I am sure, your patience is appreciated.
Thanks.
It's indeed failing before your validator gets run-- the "argument out of range" error is what happens when you call Time.parse
on a date that can't exist. In irb:
2.0.0p247 :004 > require 'time'
=> true
2.0.0p247 :005 > Time.parse("1/123/2012")
ArgumentError: argument out of range
And I'm betting that started
is a datetime
or timestamp
attribute, right? Rails tries to convert the string from the params
hash to their types before any validations are run.