4

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",
    }
  ]
}
3
  • 1
    Please post the code that does the create statement. Commented Jul 14, 2018 at 12:56
  • @Anton i updated with json Commented Jul 14, 2018 at 13:08
  • Great! Please add the controller code as well. Commented Jul 14, 2018 at 13:13

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

6 Comments

i was doing this thing before which didn't worked so i added null: false which also didn't work
Can you please add the controller code used for creation.
What does ExternalSource.new display in rails console?
sorry for late reply. internet is really bad. yeah that shows the default values. i check.
Then there is something wrong with the controller code. Remove the null: false from the migration file and check the code in controller.
|
0

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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.