Reputation:
I'm currently learning Ruby on rails with OpenClassrooms, and they are using that piece of code :
validates :name, presence: {
message: "Give a name"
}
When I try to create an object without the name, I'm not getting any error. For example :
me = Person.new name:""
me.errors.to_hash
=> {}
With the same example (just not the same classes), OpenClassrooms get an error and I don't know why I don't get any error
Upvotes: 1
Views: 3177
Reputation: 6445
Errors are added to an object after validation. When you call new
, you're not validating anything, so the object has no errors.
If you try and save it and then check the errors, you will get what you're looking for:
me = Person.new name:""
me.errors.to_hash
=> {}
me = Person.new name:""
me.save
=> false
me.errors.to_hash
=> ActiveModel::Errors...
Upvotes: 1
Reputation: 6852
Call me.validate
before checking the error object. You can also call #valid?
.
me = Person.new name: ""
me.validate
me.errors.to_hash
=> { ... }
All saving methods call this #validate
method internally, such as #save
and #save!
.
Upvotes: 1