Forum: Ruby on Rails Accessing ActiveRecord errors 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-10 17:21
(Received via mailing list)
Hi there,

I'm trying to implement Simply Accessible's form error messages
advice, explained here:

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

I'm trying to produce a custom FormBuilder to accomplish this.  It's
based on the TaggedBuilder example in the AWDWR2 book.

Of course, I can't use error_messages_on inside my FormBuilder, so I
rolled my own method to acquire the first error message (if any) for
an ActiveRecord instance, and was stunned into submission by the
results.

Could someone explain the cause of the HERE comment in my code below,
or suggest another approach?

Thanks,
Sheldon.

#---
# 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 LabellingFormBuilder < ActionView::Helpers::FormBuilder

  def first_error_message_on(label)
    ""
    # HERE Debugging shows @object is always nil at this point,
    # even though @object_name is set correctly! So we can't
    # just do:
    #
    #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
This topic is locked and can not be replied to.