Rails Upsert PG created_at 问题 [英] Rails Upsert PG created_at issue
问题描述
抱歉,如果之前有人回答过这个问题,但我找不到确切的答案.
Sorry if this has been answered before but I can't find a definite answer.
肯定有人在使用 upsert
时遇到过这个问题,你需要指定每一列,包括 created_at
和 updated_at
?
Surely someone has come across this issue when using upsert
you need to specify every column including created_at
and updated_at
?
如何在发生 upsert 时不更新 created_at
时间戳?我只想插入 created_at
一次.
How can I not update the created_at
timestamp when an upsert happens? I only want to insert created_at
once.
a = User.upsert({
name: ....,
age: ....
created_at: DateTime.now,
updated_at: DateTime.now
}, unique_by: :upsert_user_index )
推荐答案
如果您已经设置了default
,则无需提供created_at
和updated_at
code> 值,即数据库中的 now()
.它将自动采用当前时间戳.
No need to provide created_at
and updated_at
if you had already set the default
value i.e. now()
in the db. It will automatically takes the current timestamp.
a = User.upsert({
name: ....,
age: ....,
created_at: Time.now,
updated_at:Time.now
}, nil, unique_by: :upsert_user_index )
但是如果你想插入单条记录,你应该使用create
或save
.它将触发验证和回调.如果你想跳过它们,你也可以这样做.如果想在没有回调和验证的情况下在单个 sql 中插入多个条目,您应该使用 upsert_all
.
But if you want to insert a single record, you should use create
or save
. It will trigger the validations and callbacks. And if you want to skip them, you can do as well.
You should use upsert_all
if want to insert multiple entries in single sql without callbacks and validations.
这篇关于Rails Upsert PG created_at 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!