我有这个项目模型:
class Project < ActiveRecord::Base validates :status,:inclusion => { :in => ['active','closed'] } validates :title,:presence => true,:length => { :in => 4..30 } before_save :set_default_status_if_not_specified private def set_default_status_if_not_specified self.status = 'active' if self.status.blank? end end
如果我创建一个这样的新对象:
Project.create!(:title => 'Test 2',:pm_id => 1)
我收到这些错误:验证失败:状态未包含在列表中
但是状态字段应该在保存之前填写.
解决方法
那是因为它在before_save之前验证.
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
(-) save (-) valid (1) before_validation (-) validate (2) after_validation (3) before_save (4) before_create (-) create (5) after_create (6) after_save (7) after_commit
你可以尝试before_validation吗?