Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending error message in json using ruby on rails

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
like image 572
Om3ga Avatar asked Jul 23 '12 06:07

Om3ga


2 Answers

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.

like image 112
Daniel Evans Avatar answered Oct 14 '22 11:10

Daniel Evans


You really should use http status codes to tell the user what is going on, so for invalid record there is

420 Invalid Record  Record could not be saved

And then in your JSON return you could also have an error message that would return your active record / active model error messages in it to give them more information.

like image 31
nitecoder Avatar answered Oct 14 '22 10:10

nitecoder