Reputation: 2883
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?
Upvotes: 11
Views: 8802
Reputation: 164
In case it helps anyone else, I ran into this error message when saving an object with child models. Inspecting the child models, I saw a parent id populated on them even though the parent model did not have an id. I turned on logging and found that the parent model was being rolled back because of an error in an after_create block.
Upvotes: 0
Reputation: 5635
My answer doesn't exactly answer the OP's question, but this post comes up when googling the error message so I'm answering anyway.
I've got a has_many
relationship. Let's say we're using a Parent
model, and Parent has_many :child_models
.
When I call
@parent.child_models.create(params)
then Postgres complains about null values. But if I split it up everything is fine:
@child = @parent_object.child_models.build
@child.save
Another solution was to take out the NOT NULL
constraint. In that case create
returns without error, and when I look at the record later the timestamps are set. ActiveRecord must be saving the record without timestamps initially, and then going back and inserting them. (Rails 4.2.5)
Upvotes: 0
Reputation: 1951
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.
Upvotes: 6
Reputation: 6036
see below link for your solution.
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
Upvotes: 8