Rails Models: Validations and Error Messages

Rails Model files are sometimes mysterious. What goes in them? I don’t always know!
But one thing does go in them: validations! Any data coming from a source outside of your Rails app should have validation applied to it to make sure it’s the kind of thing you want.

So you added your validation(s)? But when you go to try out your app and you enter something in a form or upload a file, the validation works and catches a mistake, but WHERE ARE THE ERROR MESSAGES?

Most validations come with some kind of default error message. You can also define your own like so:
validates_uniqueness_of :name, :message => " is already taken. Choose another name, wiseguy."

If you want your error messages or the default ones to appear, you need to have this in your view file:
<%= error_messages_for 'chicken' %>
(replace chicken with the name of the model file that is being validated. In this case, it would be chicken.rb in /app/models

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment