Forum: Ruby on Rails Custom Association validation error messages?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2dddec0f7717cae77ac6bceede6be5bc?d=identicon&s=25 Ram (Guest)
on 2009-03-28 07:59
(Received via mailing list)
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 Bates' 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?
2dddec0f7717cae77ac6bceede6be5bc?d=identicon&s=25 Ram (Guest)
on 2009-03-30 07:01
(Received via mailing list)
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 + "<br/>" ) 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
This topic is locked and can not be replied to.