gr8scott06
gr8scott06

Reputation: 931

Rails: validation fails with before_create method on datetime attribute

ApiKey.create! 

Throws a validation error: expires_at can't be blank.

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 validation is removed the before_create method works on create.

Why is this? - This pattern works for other attributes, e.g. access_tokens (string), etc.

Upvotes: 5

Views: 2115

Answers (1)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42899

I would say because the before_create runs after the validation, maybe you want to replace before_create with before_validation

Note: If you leave the call back like that, it would set the expiry date whenever you run valid? or save or any active record method that fires the validation, You might want to limit this validation to the creation process only

before_validation :set_expires_at, on: :create

This will limit the function call only when the creation is run first time.

Upvotes: 12

Related Questions