Reputation: 125902
PostgreSQL supports several "Special Date/Time Inputs", strings that it interprets upon execution. Eg, 'now'
means "current transaction's start time", and 'infinity'
means "later than all other timestamps".
ActiveRecord does not seem to understand these - eg, SomeRecord.update!(updated_at: DateTime.current)
works, but SomeRecord.update!(updated_at: 'now')
tries to execute the UPDATE
query with a NULL
.
These special strings do work in Rails fixtures, because they go straight to the database. But is there a way to use them with an instantiated model?
Upvotes: 1
Views: 190
Reputation: 125902
.update_column
Eg, some_record.update_column(:updated_at, 'now')
.
Warning - this bypasses validations, callbacks, and normal setting of timestamps; it just issues an immediate UPDATE
query.
Despite that, ActiveRecord contributor Sean Griffin said "update_column
is probably the best 'hacky' answer" and that special string values like this aren't really well-supported and maybe shouldn't be. (I think I agree - it would make validation really awkward, both for ActiveRecord and in your own models.)
Given that this is a "direct to database" method, one possible compromise to avoid skipping validations and callbacks would be:
ActiveRecord::Base.transaction do
record.updated_at = Time.current # temporary value
record.save! # with validations, etc
record.update_column(:updated_at, 'now') # final value
end
A couple of other caveats I noticed for doing this in the console:
created_at
. Only after doing some_record.reload
did I see the timestamp.rails console
session uses one transaction. If I started a new console, I got a new value for 'now'Upvotes: 0
Reputation: 49870
You can set the value with raw_write_attribute(:updated_at, 'now')
Upvotes: 1