Dev Ngron
Dev Ngron

Reputation: 135

Rails 4: How to get error detail on ajax POST?

How can I get the detail of an error in a POST? For example I have the following validation: validates :name, presence: true If the user leaves the field in blank I want to warn the user about the mistake. .js file:

$.ajax({
  url:      "/warehouses/add_product",
  type:     "POST",      
  datatype: "JSON",
  data:     {name: product_name, price: product_price},      
  success:  function() {              
          $("#alert_success_product").css('display', 'block');
          $("#alert_success_product").append( "<p> Success! </p>" ); //Display success message here
  },
  error: function(e) {                             
          $("#alert_error_product").css('display', 'block');
          $("#alert_error_product").append( error );  //Display error message here
  }

view:

<!-- NOTIFICATION AREA -->
    <div class="alert alert-info alert-dismissible" id="alert_success_product" role="alert" style="display: none">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>          
    </div>
    <div class="alert alert-danger alert-dismissible" id="alert_error_product" role="alert" style="display: none">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>          
    </div>

controller:

def add_product
name = params[:name]
price = params[:price]

new_product = Product.new(name: name, price: price)

if new_product.save
  respond_to do |format|
    format.html {redirect_to root_path}
    format.json
  end
else
  #Render error in this section
end

end

Or if there's a better way of achieving this...

Upvotes: 0

Views: 171

Answers (1)

Louis
Louis

Reputation: 103

Try returning new_product.errors or new_product.errors.full_messages in the else case on your controller. On the Jquery side:

error: function(response) {                             
   console.log(response);
}

Upvotes: 2

Related Questions