PG :: NotNullViolation:ERROR:null值,但该值是通过ActiveRecords设置的

时间:2015-06-11 06:09:47

标签: ruby-on-rails ruby activerecord

我尝试使用CategoriesActiveRecords表格中创建新记录

这是我的ActiveRecords课程:

require_relative '../../database/contract'
require 'active_record'

class Category < ActiveRecord::Base
  self.table_name = Tables::CATEGORIES

  def initialize(name)
    @active = true
    @name = name
    super()
  end

end

这就是我想要做的事情:

category = Category.new('jewelery')
category.save

失败并显示错误:

PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint DETAIL: Failing row contains (089edda6-6b47-44b5-a612-0ab49987a99c, t, null). : INSERT INTO "categories" DEFAULT VALUES RETURNING "id"

看起来忽略了那些实例变量,并设置了默认值。名称列没有默认值,但其NOT NULL。 为什么不设置变量?

2 个答案:

答案 0 :(得分:0)

试试这个

class Category < ActiveRecord::Base
  self.table_name = Tables::CATEGORIES
  after_initialize :init

  def init(name)
    self.name  = name             
  end
end

答案 1 :(得分:0)

虽然不建议覆盖默认的ActiveRecord::Base构造函数,但它接受要为对象设置的属性哈希,因此您可以执行以下操作:

class Category < ActiveRecord::Base
  self.table_name = Tables::CATEGORIES

  def initialize(name)
    super({ active: true, name: name })
  end

end