
Originally Posted by
tizzod
I think the key to understanding what that custom builder is doing comes when you realise how errors are passed from the model to the view/helper. The object created from a model will carry any errors in an errors method. So:
Say you have a model Thing. In your controller you have the code:
Code:
@thing = Thing.find(params[:id])
Which means the instance of Thing you are using is passed to the view via @thing. This @thing will have a method 'errors' that contains all the current error messages for this object. So you can do this:
Code:
all_thing_errors = @thing.errors
The object returned by errors has it own set of methods including 'on' which allows you to grab the subset of errors that just apply to a particular method. So you can do this:
Code:
errors_on_thing_name = @thing.errors.on(:name) if @thing.errors
If there is only one error, errors will contain just that error but if there are more, errors will contain an array.
So you could just do:
Code:
<% errors_on_thing_name = @thing.errors.on(:name) if @thing.errors %>
<%= f.text_field :name %>
<%= content_tag('span',
(errors_on_thing_name.is_a?(Array) ? errors_on_thing_name.first : errors_on_thing_name)
) if errors_on_thing_name %>
That's fairly close to what Andrew Timberlake is doing, except he is doing it in a far neater and more flexible way. Rather than actually specifying the object being passed to the view (in my example @thing) he uses objects available to the form to grab the object. See this line:
Code:
object = @template.instance_variable_get("@#{@object_name}")
In my example I could use much of his code by simple replacing this line with:
but the result would be code that only worked for @thing.
By creating a new class ErrorFormBuilder based on the standard FormBuilder he allows a fairly simple way of adding his functionality to any form by simply adding:
Code:
:builder => ErrorFormBuilder
This means he does the job in a way that can be used in any form. Very nice.
I think this google search should give you more information on Formbuilder.
Bookmarks