Rails:验证在datetime属性上使用before_create方法失败

gr8*_*t06 3 ruby validation ruby-on-rails

ApiKey.create! 
Run Code Online (Sandbox Code Playgroud)

引发验证错误:expires_at不能为空.

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
Run Code Online (Sandbox Code Playgroud)

有属性

t.datetime :expires_at
Run Code Online (Sandbox Code Playgroud)

但是,如果删除了验证,则before_create方法适用于create.

为什么是这样? - 此模式适用于其他属性,例如access_tokens(string)等.

Moh*_*ady 9

我会说,因为before_create运行验证后,也许你要替换before_createbefore_validation

注意:如果你离开再打这样,它会设置每次运行到期日valid?save或触发该验证的任何活动记录的方法,您可能需要限制此验证的创作过程只

before_validation :set_expires_at, on: :create
Run Code Online (Sandbox Code Playgroud)

这将仅在第一次运行创建时限制函数调用.