Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>"
}
like image 758
andi Avatar asked Apr 14 '09 12:04

andi


1 Answers

The problem (for me at least) was that my f.select :whatever_id was looking in the object.errors object for a key of :whatever_id when my validation was actually on :whatever, not :whatever_id.

I worked around this annoying problem by changing

object.errors.on(@method_name)

to

object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, ''))

Here's the diff (against Rails 2.3.4):

diff --git a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
index 541899e..5d5b27e 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
@@ -247,7 +247,7 @@ module ActionView
       alias_method :tag_without_error_wrapping, :tag
       def tag(name, options)
         if object.respond_to?(:errors) && object.errors.respond_to?(:on)
-          error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name))
+          error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, '')))
         else
           tag_without_error_wrapping(name, options)
         end
@@ -256,7 +256,7 @@ module ActionView
       alias_method :content_tag_without_error_wrapping, :content_tag
       def content_tag(name, value, options)
         if object.respond_to?(:errors) && object.errors.respond_to?(:on)
-          error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name))
+          error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, '')))
         else
           content_tag_without_error_wrapping(name, value, options)
         end
like image 198
Tyler Rick Avatar answered Nov 15 '22 11:11

Tyler Rick