ruby-on-railsupsertstrong-parameters

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

Solution

  • upsert works in straight SQL with 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()' }
    

    or you could use current_timestamp as the default (which will work with both PostgreSQL and MySQL):

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

    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()'. Similarly if you use current_timestamp instead of now().