使用 upsert 时,列 "created_at" 中的空值违反了非空约束

Null value in column "created_at" violates not-null constraint when using upsert

为什么 created_at 为空,我该如何解决?

 ↳ app/controllers/projects_controller.rb:28:in `create'
  Tag Upsert (5.6ms)  INSERT INTO "tags" ("category","name") VALUES ('topic', 'career') ON CONFLICT ("id") DO UPDATE SET "type"=excluded."type","name"=excluded."name" RETURNING "id"
  ↳ app/controllers/projects_controller.rb:32:in `block in create'
Completed 500 Internal Server Error in 62ms (ActiveRecord: 31.0ms | Allocations: 22999)



ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint
DETAIL:  Failing row contains (5, topic, career, null, null).
):

app/controllers/projects_controller.rb:32:in `block in create'
app/controllers/projects_controller.rb:31:in `each'
app/controllers/projects_controller.rb:31:in `create'
# projects_controller.rb
def create
    @project = Project.create(project_params)
    if @project.valid?
      # tags
      params[:tags].each do |tag|
        @tag = Tag.upsert({ category: 'topic', name: tag })
        ProjectTag.create(tag: @tag, project: @project)
      end
      respond_to do |format|
        format.json { render json: { "message": "success!", status: :ok } }
      end
    end
  end

upsert 直接 SQL 工作,很少涉及 ActiveRecord:

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.

所以 AR 不会像往常那样接触 updated_atcreated_at

最简单的方法是添加迁移以在数据库中为 created_atupdated_at 添加默认值:

change_column_default :tags, :created_at, from: nil, to: ->{ 'now()' }
change_column_default :tags, :updated_at, from: nil, to: ->{ 'now()' }

或者您可以使用 current_timestamp 作为默认值(这将适用于 PostgreSQL 和 MySQL):

change_column_default :tags, :created_at, from: nil, to: ->{ 'current_timestamp' }
change_column_default :tags, :updated_at, from: nil, to: ->{ 'current_timestamp' }

然后数据库将处理这些列。

迁移中需要注意的两点:

  1. 传递 :from:to 选项而不是仅仅传递新的默认选项可以实现可逆迁移。
  2. 您必须对 :to 值使用 lambda,以便使用 PostgreSQL now() 函数而不是字符串 'now()'。同样,如果您使用 current_timestamp 而不是 now()