sending error message in json using ruby on rails

json, ruby, ruby-on-rails, ruby-on-rails-3

Solution

The simplest way would be to send down a hash of the errors.

so:

render :json => { :errors => @contacts.errors.as_json }, :status => 420

note that `:status => 420` is required to make things like jquery's $.ajax method call their error callback and you should never return a 200 status (the default) when there is an error.

Problem

I am validating input fields in ruby on rails. I checking whether user have entered or filled these fields or not. If lets say `name` field is not filled then send an error message to user with indication that `name` field is not filled. Same goes with other errors. How can I send this kind of message in json using ruby on rails. Here is what I am doing right now. this model ``` validates :email, :name, :company, :presence => true validates_format_of :email, :with => /\A[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z/ ``` Here is how I am currently sending json data to client ``` @contacts = Contact.new(params[:contact]) if @contacts.save render :json => { :error => 0, :success => 1 } else render :json => { :error => 1, :success => 0 } end ```

Original source