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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With