rustyshackleford
rustyshackleford

Reputation: 731

Changing a date field in a record using the rails console

I have an object stored in my database of type time. In the Rails console, if I find this particular record by its ID, I get the following output:

 id: 365,
 from_hours: Sat, 01 Jan 2000 01:00:00 UTC +00:00,
 to_hours: Sat, 01 Jan 2000 12:30:00 UTC +00:00

I'd like to update the from_hours field to Sat, 01 Jan 2000 13:00:00 UTC +00:00

How can I approach this?

I've tried using MyRecord.find(365).update(from_hours: Sat, 01 Jan 2000 13:00:00 UTC +00:00) to no avail. Thanks in advance!

Upvotes: 0

Views: 1328

Answers (2)

Sahil Grover
Sahil Grover

Reputation: 1915

If you are getting from_hours: Sat, 01 Jan 2000 01:00:00 UTC +00:00 as a variable then use

MyRecord.find(365).update(from_hours: from_hours)

otherwise use the time inside quotes such as

MyRecord.find(365).update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')

I would recommend not to use update directly because record can also return nil so better to use

if record = MyRecord.find(365)
  record.update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')
end

Upvotes: 4

racar
racar

Reputation: 181

you need to add quotes in the from_hours param:

MyRecord.find(365).update(from_hours: 'Sat, 01 Jan 2000 13:00:00 UTC +00:00')

Use .update! if you need to get the raises exceptions in the console.

Upvotes: 1

Related Questions