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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With