upsert
works in straight SQL without very little ActiveRecord involvement:
Updates or inserts (upserts) a single record into the database in a single SQL INSERT statement. It does not instantiate any models nor does it trigger Active Record callbacks or validations.
so AR won't touch updated_at
or created_at
like it usually does.
The easiest thing to do would be add a migration to add defaults in the database for created_at
and updated_at
:
change_column_default :tags, :created_at, from: nil, to: ->{ 'now()' }
change_column_default :tags, :updated_at, from: nil, to: ->{ 'now()' }
Then the database will take care of those columns.
Two things to note in the migration:
- Passing the
:from
and :to
options instead of just the new default gives you a reversible migration.
- You have to use a lambda for the
:to
value so that the PostgreSQL now()
function will be used rather than the string 'now()'
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…