我有一个Job
模型和Category
模型,我使用HABTM协会加入了该模型。
我在尝试分配给Categories_Jobs
模型时遇到错误。
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
我应该从Categories_Jobs
模型中删除时间戳吗?
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
我应该采取另一种方式吗?
答案 0 :(得分:8)
请参阅下面的解决方案链接。
您的解决方案
删除t.timestamps
,然后运行。
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
答案 1 :(得分:6)
使用另一种多对多关系声明。
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
然后你就可以使用时间戳了。
答案 2 :(得分:0)
我的回答并没有完全回答OP的问题,但是在搜索错误消息时会出现这个帖子,所以无论如何我都会回答。
我有has_many
关系。假设我们使用Parent
模型和父has_many :child_models
。
当我打电话
@parent.child_models.create(params)
然后Postgres抱怨空值。但如果我把它分开,一切都很好:
@child = @parent_object.child_models.build
@child.save
另一个解决方案是取出NOT NULL
约束。在这种情况下,create
会返回而不会出现错误,当我稍后查看记录时,会设置时间戳。 ActiveRecord必须在没有时间戳的情况下保存记录,然后返回并插入它们。 (Rails 4.2.5)
答案 3 :(得分:0)
万一它对其他人有帮助,在保存带有子模型的对象时会遇到此错误消息。检查子模型,即使父模型没有ID,我也看到了一个父ID。我打开了日志记录,发现由于after_create块中的错误,父模型正在回滚。