My Job model has job_date field that is defined in the migration file like this:
create_table :jobs do |t|
t.date "job_date", :null => false
[...]
end
In my development environment (on Windows), when I do:
job = Job.new(:job_date => "17/04/2011")
everything works fine (i.e. the job_date is set properly), while when I do:
job = Job.new(:job_date => "04/17/2011")
job_date is set to nil.
I guess this is because the database (MySQL) expects to get the date in DD/MM/YYYY format.
The problem is that in my production environment, exactly the opposite occurs, i.e.:
job = Job.new(:job_date => "04/17/2011")
sets the ‘job_date` properly, while:
job = Job.new(:job_date => "17/04/2011")
sets it to nil.
How could I solve this inconsistency ?
Is there some way to config the database for specific date format (like DD/MM/YYYY) ?
It is not a database problem, but I think it is a problem with
Date.parsemethod in Ruby. Infact when you callJob.newit is not saved to database only a new object of the model is created. I beleive Rails callDate.parsemethod to convert the string into date object and it gives a error fordd/mm/yyyyformat in my machineI think Rails escape this error and gives
nilfor such valuesI guess your production environment’s results are same like my machine and your development machine’s Ruby,
Date.parsemay be working for the other format.If you need to handle only one format(Either
dd/mm/yyyyormm/dd/yyyy), you can useDate.strptimeto calculate the date before giving to databaseThis will work both in your production and development environment for one format.