before_save不使用Rails 3

时间:2021-05-23 01:19:38

I have this Project model:

我有这个项目模型:

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

If I create a new object like this:

如果我创建一个这样的新对象:

Project.create!(:title => 'Test 2', :pm_id => 1)

I get these errors: Validation failed: Status is not included in the list But status field should get filled in before save.

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

2 个解决方案

#1


19  

That's because it validates before before_save.

那是因为它在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

You could try before_validation ?

你可以尝试before_validation吗?

#2


2  

It looks like validation happen before the before_save callbacks. Perhaps you want to try before_validation instead?

看起来验证发生在before_save回调之前。也许你想尝试before_validation而不是?

#1


19  

That's because it validates before before_save.

那是因为它在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

You could try before_validation ?

你可以尝试before_validation吗?

#2


2  

It looks like validation happen before the before_save callbacks. Perhaps you want to try before_validation instead?

看起来验证发生在before_save回调之前。也许你想尝试before_validation而不是?