Home > OS >  Facing ActiveRecord::NotNullViolation Exception: PG::NotNullViolation: ERROR: null value in column &
Facing ActiveRecord::NotNullViolation Exception: PG::NotNullViolation: ERROR: null value in column &

Time:06-06

I am facing ActiveRecord::NotNullViolation Exception: PG::NotNullViolation: ERROR: null value in column "item_id" violates not-null constraint error while attempting to create attempts for from the controller. I have no idea how to resolve this error. Any help would be appreciated. I tried googling around to no avail. There was an issue raised in the paper_trail gem's repository in 2019 by pedrofurtado which suggested the removal of gem 'activerecord-suppress_range_error' which I am not using.

My controller looks like -

# frozen_string_literal: true

class AttemptsController < ApplicationController
  before_action :set_training
  before_action :set_attempt, only: [:update]

  def new
    @attempt = Attempt.new
    @questions = @training.questions
    skip_authorization
  end

  def create
    @attempt = @training.attempts.new(attempt_params)
    @attempt.option_id << attempt_params[:option_id]
    byebug
    @attempt.save
    skip_authorization
  end

  private

  def attempt_params
    params.require(:attempt).permit(:question_id, :user_id, :option_id)
  end

  def set_attempt
    @attempt = Attempt.find(params[:id])
  end

  def set_training
    @training = Training.find(params[:training_id])
  end
end

Migration -

# frozen_string_literal: true

class CreateAttempts < ActiveRecord::Migration[6.1]
  def change
    create_table :attempts, type: :uuid do |t|
      t.references :user, type: :uuid, index: true, foreign_key: true, null: false
      t.references :training, type: :uuid, index: true, foreign_key: true, null: false
      t.string :option_id, array: true, default: [], null: false
      t.string :question_id, null: false

      t.timestamps
    end
  end
end

My rails version is 6.1.3. Ruby version is 2.7.5 Paper trail gem's version is 11.0

CodePudding user response:

I solved this one myself. The issue was the attempts table whose id was not set to UUID, and the versions table where the item_id was defined was refusing to update it because when the instance of attempts was not being saved it was rolling back. Instead of setting the id as UUID, I had set the table's type as UUID.

  • Related