problems
problems

Reputation: 115

ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR: null value in column "created_at" violates not-null constraint

I have a new model, this is my migration:

def change
    create_table :news do |t|
      t.string :title
      t.text :content

      t.timestamps
    end
  end

and this is my schema

  create_table "news", force: :cascade do |t|
    t.string "title"
    t.text "content"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

I also have a policy (from pundit) for this model and a new_policy_test, however, at the moment both are empty.

So when passing the tests in Travis it tells me:

NewPolicyTest#test_update:
ActiveRecord::NotNullViolation: PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint
DETAIL:  Failing row contains (1, MyString, MyText, null, null).

and the same for NewPolicyTest#test_update, NewPolicyTest#test_scope, NewPolicyTest#test_show, NewPolicyTest#test_destroy, NewPolicyTest#test_create.

What should I do for Travis not to give me this error?

Upvotes: 2

Views: 5899

Answers (3)

Pulkit Goyal
Pulkit Goyal

Reputation: 5664

One reason this happens is when the model name is plural like in the question (model News for table news).

The solution to this is to update config/initializers/inflections.rb with:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.uncountable "news"
end

Upvotes: 0

problems
problems

Reputation: 115

I added created_at and updated_at fixtures to my news.yml file.

one:
  title: MyString
  content: MyText
  created_at: <%= 5.day.ago.to_s(:db) %>
  updated_at: <%= 5.day.ago.to_s(:db) %>

Upvotes: 3

Sadda Qayyum
Sadda Qayyum

Reputation: 11

You should have

t.timestamps

in your migration instead of

t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false

it will then populate the fields automatically when a record is created or updated.

Upvotes: 0

Related Questions