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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With