Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PG::Error: ERROR: null value in column "created_at" when inserting records into associated model

I have a Job model and a Category model which I've joined using a HABTM association.

I'm getting an error when trying to assign to Categories_Jobs model.

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

j = Job.first
Job Load (0.7ms)  SELECT "jobs".* FROM "jobs" LIMIT 1
=> #<Job id: 7, user_id ...(removed rest of details for sake of clarity)

j.categories
Category Load (0.8ms)  SELECT "categories".* FROM "categories" INNER JOIN "categories_jobs" ON "categories"."id" = "categories_jobs"."category_id" WHERE "categories_jobs"."job_id" = 7
=> [] 

j.category_ids = [1]
Category Load (6.1ms)  SELECT "categories".* FROM "categories" WHERE "categories"."id" =   $1 LIMIT 1  [["id", 1]]
(0.2ms)  BEGIN
(0.6ms)  INSERT INTO "categories_jobs" ("job_id", "category_id") VALUES (7, 1)
(0.1ms)  ROLLBACK
ActiveRecord::StatementInvalid: PG::Error: ERROR:  null value in column "created_at" violates not-null constraint

Should I remove the timestamps from my Categories_Jobs model?

class CreateCategoriesJobs < ActiveRecord::Migration
  def change
    create_table :categories_jobs, :id => false do |t|
      t.integer :category_id
      t.integer :job_id
      t.timestamps
    end
  end
end

Should I be doing this another way?

like image 424
Robert B Avatar asked Oct 19 '12 06:10

Robert B


2 Answers

see below link for your solution.

HABTM

your solution

remove t.timestamps and then run.

class CreateCategoriesJobs < ActiveRecord::Migration
  def change
    create_table :categories_jobs, :id => false do |t|
      t.integer :category_id
      t.integer :job_id
    end
  end
end
like image 156
Dipak Panchal Avatar answered Nov 02 '22 18:11

Dipak Panchal


Just use another kind of many-to-many relation declaration.

class Category ...

  has_many :categories_jobs
  has_many :categories, through: :categories_jobs

  ...
end

class Job ...

  has_many :categories_jobs
  has_many :jobs, through: :categories_jobs

  ...
end

then you will be able to use timestamps.

like image 6
Nickolay Kondratenko Avatar answered Nov 02 '22 18:11

Nickolay Kondratenko