Luiz E.
Luiz E.

Reputation: 7229

before_create not being invoked

I have this class

class APIKey < ActiveRecord::Base

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

and when I try to create a new record with APIKey.create! I get this erro

  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

What am I missing?

Upvotes: 2

Views: 338

Answers (1)

fgp
fgp

Reputation: 428

The validation of the record happens before the before_create callback is called. You should set your attributes in the before_validation callback.

If you want more information about ActiveRecord's callbacks you may check RailGuides

Upvotes: 4

Related Questions