Search code examples
ruby-on-railsvalidationactionviewfield-with-errors

Rails validation and 'fieldWithErrors' wrapping select tags


Is it normal behaviour to not get the <div class="fieldWithErrors"> wrapped arround select tags that have validation errors? I personally see no reason why the select tags should be treated differently than other form tags (input, textarea).

I do get the error in error_messages_for and error_message_on methods for that field.

PS. I have altered a bit the ActionView::Base.field_error_proc in order to get span tags instead of divs, but that isn't the problem.

ActionView::Base.field_error_proc = Proc.new { |html_tag, instance|
   #if I puts html_tag here I only get the <input> tags
   "<span class=\"fieldWithErrors\">#{html_tag}</span>"
}

Solution

  • Because I couldn't find out why the select tags were not included in that Proc, I created a helper method which does preety much the same thing.

    def field_with_error(object, method, &block)
      if block_given?
        if error_message_on(object, method).empty?
          concat capture(&block)
        else
          concat '<span class="fieldWithErrors">' + capture(&block) + '</span>'
        end
      end
    end
    

    I use it in my views like so:

    <% field_with_error @some_object, :assoc do %>
      <%= f.select(:assoc_id, @associations.collect {|assoc| [ asoc.name, assoc.id ] }) %>
    <% end %>
    

    If anybody knows a better or cleaner way to do it, I'm open to suggestions.