Mani
Mani

Reputation: 2563

Null constraint error while Default value is set Ruby On Rails - Postgresql

In my database i have a table with schema like below

  create_table "external_source", force: :cascade do |t|
    t.string   "external_id"
    t.string   "permalink",                             null: false
    t.datetime "created_at",                            null: false
    t.datetime "updated_at",                            null: false
    t.boolean  "is_deleted",         default: false,    null: false
    t.string   "company_name",       default: ""
    t.boolean  "hide_salary",        default: true,     null: false
  end

But when i tried to insert values without is_deleted parameter, Rails server throws null constraint violation error like:

ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR: null value in column "is_deleted" violates not-null constraint

Now when I have set its default value I am not expecting this error. can you tell me what wrong am I doing. Thank You

here is the JSON to insert

{
  "data":
  [
    {
      "external_id":"2262a0228sf-1b9e-sd4e76-b5d7-a8ba01783ebb9i3413139",
      "permalink": '234242341',
      "hide": true,
      "company_name": "com1",
    }
  ]
}

Upvotes: 4

Views: 2292

Answers (2)

MaciekR
MaciekR

Reputation: 292

Maybe there is a validation in model, sth like validates :is_deleted, presence: true? if so:

  • get rid of this validation, or
  • keep validation and set as false by default (if missing), i.e.

    def default_deleted_status
      self.status ||= false
    end
    

Upvotes: 0

Shabini Rajadas
Shabini Rajadas

Reputation: 761

null and default have different purposes in the migration. If you want the default value to be set as false, when no value is set in the controller just use,

default: false,

there is no need to use the null:false parameter in your case. default would do the work for you. For more explanation of null and default please check the following link How do :default => 0 and :null => false differ for integer fields in migrations?

Upvotes: 2

Related Questions