Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: seeding database data and date formats

I'm trying to seed some data into a Rails 3 app that I'm developing, using the db/seed.rb file and the rake db:seed command.

The data I'm seeding involves a database table called Meeting that has three columns: string title, datetime startDate, datetime endDate. The datetimes I'm trying to insert are in "mm/dd/yyyy hh:mm" format -- eg. "01/02/2003 13:23" = January 2, 2003 1:23 PM. However, the DateTime.parse() is consistently erroring out with an "invalid date" error -- as it tries to parse the dates in "dd/mm/yyyy" format.

From my Googling, I've been led to believe that when parsing DateTime objects the compiler looks at the string that's passed in and does some hasty pattern matching and then maps "mm/dd/yyyy" and "dd-mm-yyyy" accordingly per American/British(etc) standards based on whether a slash or a dash was used as a seperator. This doesn't seem to be the case, however, and I'm wondering why. And how to fix it.

This is how I'm seeding the Meetings -- the first one parses properly, the second one fails.

Meeting.create([
  {
    :title => "This meeting parses fine",
    :startDate => DateTime.parse("09/01/2009 17:00"),
    :endDate => DateTime.parse("09/01/2009 19:00")
  },
  {
    :title => "This meeting errors out",
    :startDate => DateTime.parse("09/14/2009 8:00")
    :endDate => DateTime.parse("09/14/2009 9:00")
  }])
like image 200
Roddy of the Frozen Peas Avatar asked Mar 29 '11 14:03

Roddy of the Frozen Peas


People also ask

What is data seeding in rails?

What is Seed in Rails ? A useful way of populating a database with the initial data needed for a Rails project. This will allow us to populate the database in within our Rails Web application.

What is seed rb file?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb. rake db:setup.

What seed data means?

Data seeding is the process of populating a database with an initial set of data.


1 Answers

Use DateTime.new instead. No worries about proper parsing then.

Meeting.create([
  {
    :title      => "This meeting parses fine",
    :startDate  => DateTime.new(2009,9,1,17),
    :endDate    => DateTime.new(2009,9,1,19)
  },
  {
    :title      => "This meeting errors out",
    :startDate  => DateTime.new(2009,9,14,8),
    :endDate    => DateTime.new(2009,9,14,9)
  }
])
like image 123
Douglas F Shearer Avatar answered Sep 30 '22 20:09

Douglas F Shearer