before_create未被调用

时间:2014-05-28 16:28:10

标签: ruby-on-rails activerecord ruby-on-rails-4

我有这个班级

class APIKey < ActiveRecord::Base

  before_create do 
    self.token = SecureRandom.urlsafe_base64
    self.valid_token = true
  end
end

当我尝试使用APIKey.create!创建新记录时,我得到了这个错误

  SQL (56.5ms)  INSERT INTO "api_keys" ("created_at", "token", "updated_at", "valid_token") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", nil], ["token", nil], ["updated_at", nil], ["valid_token", nil]]
PG::NotNullViolation: ERROR:  null value in column "token" violates not-null constraint

我错过了什么?

1 个答案:

答案 0 :(得分:2)

记录的验证发生在调用before_create回调之前。您应该在before_validation回调中设置属性。

如果您想了解有关ActiveRecord回调的更多信息,可以查看RailGuides