I do have a model within a Rails application with the following definition (I am using Mongoid):
field :date, type: Date
I included the field within the view as a text_field (f.text_field). Everything works fine, if I do enter a valid date. But when I enter some text in this field (e.g. 'foo'), then the date gets parsed as 01.01.1970. I am not parsing the date manually, rather I use the following code:
#offer = Offer.new(offer_params)
I also checked on the Ruby console:
>> offer = Offer.new
...
>> offer.date = 'foo'
"foo"
>> offer.date
Thu, 01 Jan 1970
>> offer.date.is_a? Date
true
How can I prevent this behavior so that the record can't be saved and a validation error gets shown to the user?
Thanks for your help!
You can modify the Offer initializer so that it will use the Date::parse method for parsing your date. This will throw an ArgumentError, when the parameter you supply to it is not a valid date format.
You may have to convert that to seconds since 1.1.1970 as that seems to be the format used for storing your dates in your database. Have a look at Date#strftime for that.
I would like to write inclusion validator like below:
validates :application_date,
inclusion_of: { in: Date.today..20.years.from_now }
# Schema
# application_date :date
But I get
bad value for range
The reason you're getting that error is because 20.years.from_now is returning a datetime object (ActiveSupport::TimeWithZone) and Date.today returns a date. Therefor your range will not work because it's using two different object types. You might be able to fix it by converting the latter to a date:
Date.today..20.years.from_now.to_date
I'm in the U.S., and we usually format dates as "month/day/year". I'm trying to make sure that my Rails app, using Ruby 1.9, assumes this format everywhere, and works the way it did under Ruby 1.8.
I know that lots of people have this issue, so I'd like to create a definitive guide here.
Specifically:
'04/01/2011' is April 1, 2011, not Jan 4, 2011.
'4/1/2011' is also April 1, 2011 - the leading zeros should not be necessary.
How can I do this?
Here's what I have so far.
Controlling Date#to_s behavior
I have this line in application.rb:
# Format our dates like "12/25/2011'
Date::DATE_FORMATS[:default] = '%m/%d/%Y'
This ensures that if I do the following:
d = Date.new(2011,4,1)
d.to_s
... I get "04/01/2011", not "2011-04-01".
Controlling String#to_date behavior
ActiveSupport's String#to_date method currently looks like this (source):
def to_date
return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end
(In case you don't follow that, the second line creates a new date, passing in year, month and day, in that order. The way it gets the year, month and day values is by using Date._parse, which parses a string and somehow decides what those values are, then returns a hash. .values_at pulls the values out of that hash in the order Date.new wants them.)
Since I know that I will normally pass in strings like "04/01/2011" or "4/1/2011", I can fix this by monkeypatching it like this:
class String
# Keep a pointer to ActiveSupport's String#to_date
alias_method :old_to_date, :to_date
# Redefine it as follows
def to_date
return nil if self.blank?
begin
# Start by assuming the values are in this order, separated by /
month, day, year = self.split('/').map(&:to_i)
::Date.new(year, month, day)
rescue
# If this fails - like for "April 4, 2011" - fall back to original behavior
begin
old_to_date
rescue NoMethodError => e
# Stupid, unhelpful error from the bowels of Ruby date-parsing code
if e.message == "undefined method `<' for nil:NilClass"
raise InvalidDateError.new("#{self} is not a valid date")
else
raise e
end
end
end
end
end
class InvalidDateError < StandardError; end;
This solution makes my tests pass, but is it crazy? Am I just missing a configuration option somewhere, or is there some other, easier solution?
Are there any other date-parsing cases I'm not covering?
Gem: ruby-american_date
This gem was created since I asked this question. I'm now using it and have been pleased.
https://github.com/jeremyevans/ruby-american_date
Date.strptime is probably what you're looking for in ruby 1.9.
You're probably stuck monkeypatching it onto string.to_date for now, but strptime is the best solution for parsing dates from strings in ruby 1.9.
Also, the formats are symmetric with strftime as far as I know.
you can use rails-i18n gem or just copy the en-US.yml and set your default locale "en-US" in config/application.rb
For parsing US-style dates, you could use:
Date.strptime(date_string, '%m/%d/%Y')
In console:
> Date.strptime('04/01/2011', '%m/%d/%Y')
=> Fri, 01 Apr 2011
> Date.strptime('4/1/2011', '%m/%d/%Y')
=> Fri, 01 Apr 2011
Use REE? :D
Seriously though. If this is a small app you have complete control over or you are standardizing on that date format, monkey patching for a project is totally reasonable. You just need to make sure all your inputs come in with the correct format, be it via API or website.
Instead of using to_s for Date instances, get in the habit of using strftime. It takes a format string that gives you complete control over the date format.
Edit:
strptime gives you full control over the parsing by specifying a format string as well. You can use the same format string in both methods.
Another option is Chronic - http://chronic.rubyforge.org/
You just need to set the endian preference to force only MM/DD/YYYY date format:
Chronic::DEFAULT_OPTIONS[ :endian_precedence ] = [ :middle ]
However the default for Chronic is the out-of-order US date format anyway!
Say for instance I have a datefield or 3 select fields for day month and yea..
How does the final selection of date get sent to the database? or in what format doesn't it get sent?
20110803 ?
2011-08-03 ?
What I want to do is:
Test for a valid date (a date that has been selected that exists)
Test for an invalid date (invalid would be a date that doesn't exist and also be when nothing has been selected)
I know an idea of how to write these tests but not sure what actually gets sent to the database
What actually appears before save and in what format. String? Integer?
Thanks in advance for responses.
The gets sent to the database as the database expects it. Each database and configuration will yield a different format for a date but this will not make any difference to you as the field is configured to be Date and it will also be a Date on Rails, so you should not care about the format.
While testing, there are many ways you can validate, but you will not be using neither integer or string, you're using Date objects. Here's an example of how you could write the first one:
it 'should find a model today' do
#date = Date.today
#model = Model.create!(:date => #date)
Model.first( :conditions => {:date => #date}).should == #model
end
I've run into a spot of bother with date formats in our Rails application.
I have a date field in our view which I want to be formatted as dd/mm/yy. This is how the user will expect to enter their dates, and the datepicker control uses this format.
However, Active Record seems to be expecting mm/dd/yy.
If I enter 01/03/2010, this gets put in as 03 January 2010.
If I enter 25/03/2010, this gets put in a null.
How do I get ActiveRecord to expect Her Majesties date format?
Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy or dd-mm-yy or yyyy-mm-dd or yyyy/mm/dd. You could monkey-patch DateTime.parse, but I would rather move this issue to the View of your application.
I always recommend to use yyyy-mm-dd [hh:mm:ss] as a string representation for a date. Check the documentation of your DatePicker if it supports multiple date-formats.
The jQuery date-picker for example has this covered with dateFormat (for the data that is sent to the server, set this to yyyy-mm-dd) as well as altFormat (for the input the user sees, set this to dd/mm/yyyy).
Add a file called rails_defaults.rb to config\initializers directory; with following lines:
Date::DATE_FORMATS[:default] = '%d/%m/%Y'
Time::DATE_FORMATS[:default]= '%d/%m/%Y %H:%M:%S'
Restart the server and you are good to go.
class Date
class << self
def _parse_with_us_format(date, *args)
if date =~ %r{^(\d+)/(\d+)/(\d+)$}
_parse_without_us_format("#{$3.length == 2 ? "20#{$3}" : $3}-#{$1}-#{$2}", *args)
else
_parse_without_us_format(date, *args)
end
end
alias_method_chain :_parse, :us_format
end
end