Aaron
Aaron

Reputation: 4480

How to save a date into rails using the console

I have a table that has a date field in it. How would I save the date using the console? I tried event = Event.create(name:"Concert", date:08/20/2016, location:'Portland', state:'OR') However, I am getting an Invalid octal digit error.

Upvotes: 8

Views: 8941

Answers (3)

James
James

Reputation: 4737

Using a string in the correct format will do the trick. For example:

>> foo = Foo.create date: "20/8/2016"
   (0.0ms)  begin transaction
  SQL (1.0ms)  INSERT INTO "foos" ("date") VALUES (?)  [["date", Sat, 20 Aug 2016]]
   (0.9ms)  commit transaction
#<Foo id: 1, date: "2016-08-20">
>> foo.date
Sat, 20 Aug 2016

ActiveSupport provides core extensions on the String class for conversions from strings to date, time, and datetime. This is probably ok, and more convenient, to take advantage of while testing around in Rails console.

Taking advantage of this extension in the application itself (instead of explicitly parsing with Date.parse) is totally up to you and your team.

From the source:

"1-1-2012".to_date   # => Sun, 01 Jan 2012
"01/01/2012".to_date # => Sun, 01 Jan 2012
"2012-12-13".to_date # => Thu, 13 Dec 2012
"12/13/2012".to_date # => ArgumentError: invalid date

Just to be thorough, examples for String#to_time

"13-12-2012".to_time               # => 2012-12-13 00:00:00 +0100
"06:12".to_time                    # => 2012-12-13 06:12:00 +0100
"2012-12-13 06:12".to_time         # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time         # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time(:utc)   # => 2012-12-13 06:12:00 UTC
"12/13/2012".to_time               # => ArgumentError: argument out of range

And String#to_datetime:

"1-1-2012".to_datetime            # => Sun, 01 Jan 2012 00:00:00 +0000
"01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
"2012-12-13 12:50".to_datetime    # => Thu, 13 Dec 2012 12:50:00 +0000
"12/13/2012".to_datetime          # => ArgumentError: invalid date

Upvotes: 3

Hasmukh Rathod
Hasmukh Rathod

Reputation: 1118

Try this, for example:

date = Date.parse('3rd Feb 2001')  ####=> #<Date: 2001-02-03 ...>

Reference: Date class

Upvotes: 2

Robert Nubel
Robert Nubel

Reputation: 7522

You'll want to pass in an actual Date object, which you can get from a string with the Date.parse method:

event = Event.create(name: "Concert", date: Date.parse('2016-08-20'), location: 'Portland', state: 'OR')

Note that I've rewritten your date to be in a different format. The MM/DD/YYYY format is not portable across locales, so I'd strongly suggest you use YYYY-MM-DD (the ISO 8601 format).

Upvotes: 12

Related Questions