before_save not working with Rails 3

Posted by Mich Dart on Stack Overflow See other posts from Stack Overflow or by Mich Dart
Published on 2012-06-17T15:08:25Z Indexed on 2012/06/17 15:16 UTC
Read the original article Hit count: 137

Filed under:

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.

© Stack Overflow or respective owner

Related posts about ruby-on-rails