11

我有一个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

我应该以另一种方式这样做吗?

4

4 回答 4

8

请参阅下面的链接以获取您的解决方案。

HABTM

你的解决方案

删除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
于 2012-10-19T06:20:43.673 回答
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

那么您将能够使用时间戳。

于 2012-12-26T09:13:12.087 回答
0

如果它对其他人有帮助,我在保存带有子模型的对象时遇到了这个错误消息。检查子模型,即使父模型没有 id,我也看到在它们上填充了父 id。我打开了日志记录,发现由于 after_create 块中的错误,父模型正在回滚。

于 2019-12-24T15:30:08.280 回答
0

我的回答并没有完全回答 OP 的问题,但是在谷歌搜索错误消息时会出现这篇文章,所以我还是要回答。

我有has_many关系 假设我们正在使用Parent模型和 Parent has_many :child_models

当我打电话

@parent.child_models.create(params)

然后 Postgres 抱怨空值。但如果我把它分开,一切都很好:

@child = @parent_object.child_models.build
@child.save

另一种解决方案是消除NOT NULL约束。在那种情况下create返回没有错误,当我稍后查看记录时,时间戳已设置。ActiveRecord 最初必须保存没有时间戳的记录,然后返回并插入它们。(导轨 4.2.5)

于 2016-04-12T21:21:55.897 回答