Rails: validation fails using before_create method on datetime attribute
ApiKey.create!
Throws a validation error: expires_at cannot be empty.
class ApiKey < ActiveRecord::Base
before_create :set_expires_at
validates :expires_at, presence: true
private
def set_expires_at
self.expires_at = Time.now.utc + 10.days
end
end
with attribute
t.datetime :expires_at
However, if the check is removed, the before_create method works on create.
Why is this? - This pattern works for other attributes eg. access_tokens (string) etc.
source to share
I would say because it before_create
starts after checking, perhaps you want to replace before_create
withbefore_validation
Note. If you leave the callback this way, it will set an expiration date whenever you run valid?
or save
or any active write method that triggers a check, you might want to limit this check to the create process only
before_validation :set_expires_at, on: :create
This will restrict the call to the function only if the creation is done for the first time.
source to share