before_save不使用Rails 3

时间:2012-06-17 15:08:26

标签: ruby-on-rails

我有这个项目模型:

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)

我收到以下错误:验证失败:状态未包含在列表中 但是状态字段应该在保存之前填写。

2 个答案:

答案 0 :(得分:19)

这是因为它在 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吗?

答案 1 :(得分:2)

It looks like验证发生在before_save回调之前。也许你想尝试before_validation