简体   繁体   中英

before_save not working with Rails 3

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.

That's because it validates before 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM