user11526842
user11526842

Reputation:

How to get validations error messages in Ruby on rails?

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

Answers (2)

Mark
Mark

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

justapilgrim
justapilgrim

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

Related Questions