# Custom Association validation error messages?

**URL:** <https://www.ruby-forum.com/t/custom-association-validation-error-messages/164124>\
**Category:** Rails\
**Created:** [March 28, 2009, 7:59am UTC](https://www.ruby-forum.com/t/custom-association-validation-error-messages/164124 "2009-03-28T07:59:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ram](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/b9bd4f/32.png) [@ram](https://www.ruby-forum.com/u/ram)\
**Post date:** [March 28, 2009, 7:59am UTC](https://www.ruby-forum.com/t/custom-association-validation-error-messages/164124/1 "2009-03-28T07:59:59Z")

</div>

Hi,

Consider 2 models Project and Task with Project has\_many Tasks and  
Task belongs\_to Project.

In a multi model form where I accept the Project name and its task  
names (Ryan B.’ complex forms 3), when I have a  
validates\_presence\_of :name for the Task model, the error messages  
that show up for two blank tasks is

Task is invalid  
Task is invalid  
Name cannot be blank  
Name cannot be blank

Now ive got error\_messages\_for overridden to display only the messages  
i pass to it. But I dont know how to remove the “Task is invalid” part  
of it. It is completely unnecessary for me. How can I remove that  
default error message for the associated model?

---

<div class="post-metadata">

**Author:** ![ram](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/b9bd4f/32.png) [@ram](https://www.ruby-forum.com/u/ram)\
**Post date:** [March 30, 2009, 7:01am UTC](https://www.ruby-forum.com/t/custom-association-validation-error-messages/164124/2 "2009-03-30T07:01:40Z")

</div>

I have a quick solution for this for now. Its a very ugly hack. If  
someone has a better way to handle this, please do enlighten…

This is the modified error\_messges\_for method in application\_helper.rb  
with the ugly hack. (Rails 2.1.0 and before)

def error\_messages\_for(\*params)  
options = params.extract\_options!.symbolize\_keys  
if object = options.delete(:object)  
objects = [object].flatten  
else  
objects = params.collect {|object\_name| instance\_variable\_get  
("@#{object\_name}") }.compact  
end  
count = objects.inject(0) {|sum, object| sum +  
object.errors.count }  
unless count.zero?  
html = {}  
[:id, :class].each do |key|  
if options.include?(key)  
value = options[key]  
html[key] = value unless value.blank?  
else  
html[key] = ‘validation\_error’  
end  
end  
options[:object\_name] ||= params.first  
error\_messages = objects.map {|object| object.errors.collect{ |  
column,error| content\_tag( :span, error + “  
” ) unless error ==  
“is invalid”} }  
#The above line is where i remove the column from the error  
message, and also the error itself if it says “is invalid”  
contents = ‘’  
contents \<\< content\_tag(:div, error\_messages)

```
   content_tag(:div, contents, html)
 else
   ''
 end

```

end
