Tuesday, September 13, 2011

How to display an error message to the user, just like ActiveRecord's validators

The default validation handling of the activerecord validators is pretty nifty, in that it automatically does so much for you, like giving the view messages to display to the user, automatically saving user input in the form, etc. Here's how to manually throw an error that functions just like the validator errors.

In your model:

before_validation do
  if something
    self.errors.add(:some_field, "already exists")
  end
end

If you have the appropriate setup in your rails form to display the error messages:

<% if @model.errors.any? %>
  <% @model.errors.full_messages.each do |msg| %>
    <%= msg %>
  <% end %>
<% end %>

Then when you do an @model.save with invalid data, your view will automatically display the following to the user:
"some_field already exists"

To simply throw something that halts execution, do a:
raise "something here"

Then you'd get a full stop error message and stack trace.

No comments:

Post a Comment