Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

Why is created_at null and how would I resolve this?

 ? 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
question from:https://stackoverflow.com/questions/65545763/null-value-in-column-created-at-violates-not-null-constraint-when-using-upsert

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. Passing the :from and :to options instead of just the new default gives you a reversible migration.
  2. You have to use a lambda for the :to value so that the PostgreSQL now() function will be used rather than the string 'now()'.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...