Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-4ruby-on-rails-3.2ruby-on-rails-3.1

fields that don't pass validations don't get .field_with_errors class


My validations work fine

class Owner < ActiveRecord::Base
validates :car_number, :name, :phone, presence:true
validates_uniqueness_of :car_number 
has_many :cars
has_many :visits
accepts_nested_attributes_for :visits

and my save.js.erb

$("ul.errors").html("")
<% if  @owner.errors.any? %>
<% @owner.errors.full_messages.each do |message| %>
$("ul.errors").append($("<li />").html("<%= message.html_safe %>"))
$('.field_with_errors').addClass('has-error has-feedback');

<% end
else %>

$("#new_owner_div").html("<%= j (render 'visits/show', { :f => @visit })%>")
<%end%>

but no fields get under class 'field_with_errors'.


Solution

  • Ok, as always, troubles that takes much time to resolve are easier than I thought.

    I found how to for each error's input by this [ assuming your inputs are named: modelname[field_name]

     <% @owner.errors.each do |attribute, error| %>
    $('[name="owner[<%=attribute%>]"]').addClass('field_with_errors')
    <% end %>
    

    where in css:

    .field_with_errors {
                 border: 2px solid red
                    }