Sending error message in json using ruby ​​on rails

I am checking input fields in ruby ​​on rails. I check if the user is entered or filled in these fields or not. If it allows you to say that the field nameis empty, send an error message to the user indicating that the field nameis empty. The same thing happens with other errors. How can I send such a message to 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/

This is how I am sending json data to the client right now

@contacts = Contact.new(params[:contact])

if @contacts.save
  render :json => { :error => 0, :success => 1 }
else
  render :json => { :error => 1, :success => 0 }
end
+5
source share
2 answers

The easiest way is to send an error hash.

So:

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

, :status => 420 , , jquery $.ajax, , 200 ( ) .

+15

http, , ,

420 Invalid Record  Record could not be saved

JSON , / , .

+1

All Articles