Forum: Ruby on Rails Accessing error messages in a custom FormBuilder

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.
Aec50f31361352a2c27ca949f64d7213?d=identicon&s=25 Sheldon Hearn (Guest)
on 2007-01-19 16:30
(Received via mailing list)
Hi there,

I'm trying to create a FormBuilder called LabellingBuilder, to
implement Simply Accessible's form error messages strategy:

http://simplyaccessible.org/article/form-error-messages

The problem is that
ActionView::Helpers::ActiveRecordHelper#error_messages_on isn't
available in subclasses of ActionView::Helpers::FormBuilder.

So I tried to write my own little error fetcher and was stunned by the
results -- while @object_name is correctly set, @object is nil, as
indicated by the XXX comment in the code below.

Can anyone help me with this code?

#---
# Based on:
# TaggedBuilder from "Agile Web Development with Rails, 2nd Ed."
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails2 for more
# book information.
#
class LabellingBuilder < ActionView::Helpers::FormBuilder

  def first_error_message_on(label)
    ""
    # XXX @object is always nil
    #errors = @object.errors.on(label)
    #errors.respond_to? :first ? errors.first : errors
  end

  #  <div class="labelled-form-input">
  #    <label for="product_description">
  #      Description
  #      <em>is too short</em>
  #    </label>
  #    <br/>
  #    <%= form.text_area 'description'  %>
  #  </div>
  def self.create_tagged_field(method_name)
    define_method(method_name) do |label, *args|
      @template.content_tag("div",
        @template.content_tag("label",
          label.to_s.humanize +
          @template.content_tag("em",
            first_error_message_on(label)),
          :for => "#{@object_name}_#{label}") +
        "<br/>" +
        super,
        :class => "labelled-form-input")
    end
  end

  field_helpers.each do |name|
    create_tagged_field(name)
  end

end
#---

Thanks in advance,
Sheldon.
This topic is locked and can not be replied to.