Showing errors in Rails with Ajax

2

I have a form with ajax that I show in a modal, but if this modal does not comply with the requirements the form does not pass, but it does not show which are the errors of the form, I hope you can help me:

contacts / shared / _error.html.erb

<div id="error_explanation">
   <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this @contact from being saved:</h2>
   <ul>
   <% @contact.errors.full_messages.each do |message| %>
     <li><%= message %></li>
   <% end %>
   </ul>
 </div>

contact_form.html.erb

<div class="row">
  <div class="small-12 columns">
    <h6>Formulario de contacto</h6>
  </div>
</div>

<%= form_for @contact, remote: true, authenticity_token: true do |f| %>
<% if @contact.errors.any? %>
<% end %>


  <div class="expanded row">
    <div class="small-6 columns">
      <%= f.email_field :email, placeholder: "Correo electronico" %>
    </div>
    <div class="small-6 columns">
      <%= f.text_field :phone, placeholder: "Telefono de contacto" %>
    </div>
  </div>

  <div class="expanded row">
    <div class="input-group small-12 columns">
      <%= f.text_field :title, placeholder: "Titulo del mensaje" %>
    </div>
    <div class="input-group small-12 columns">
      <%= f.text_area :content, placeholder: "Contenido del mensaje", :rows => 10, :cols => 120 %>
    </div>
  </div>

  <div class="row">
    <div class="actions small-12 columns">
      <%= f.submit "Enviar mensaje", class: "button" %>
    </div>
  </div>

<% end %>

create.js.erb

<% if @contact.errors? %>
  $("#error_explanation").html('<%= j render partial: "shared/error" %>');
<% else %>
  $('#exampleModal1').foundation('close');
  $(".notice").html('<%= j render partial: "layouts/alerts" %>');
  alert("Success!");
<% end %>

contact_controller.rb

def create
  @contact = Contact.new(contact_params)

  respond_to do |format|
    if @contact.save
      ContactMailer.contact_email(@contact).deliver
      format.html { redirect_to root_path, notice: 'Contact was successfully created.' }
      format.js {}
      format.json { render :show, status: :created, location: @contacts }
    else
      format.html { render :new }
      format.js {}
      format.json { render json: @contact.errors, status: :unprocessable_entity }
    end
  end
end
    
asked by Hector Hernandez 18.12.2016 в 18:20
source

0 answers