Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

before_save not working with Rails 3

Tags:

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.

like image 763
Mich Dart Avatar asked Jun 17 '12 15:06

Mich Dart


1 Answers

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 ?

like image 85
Trip Avatar answered Dec 26 '22 10:12

Trip