Model Validation via AJAX
In the last chapter we successfully separated the tweet form from the list. It’s time to add form validations – we should display an error message if the tweet text is empty.
GUI and models

Almost every form has a backing model it is connected to. Whereas the form is the model’s GUI counterpart collecting input, the models job is to validate and save this data.
When it comes to wiring presentation to models, small fine-grained widgets strike again.
Validation in models
First, we setup some constraints.
Using form helpers
In the next step we use Rails’ form helpers for setting up the input field quickly.
The #form_for does all the work for us (line 4). When clicking the “Tweet!” button, the form is submitted and triggers a :submit event in Rails.
Errors from validation are showed with error_messages (line 6).
Notice how you can use Rails helpers in widget views. If you need a special helper that’s not around automatically, use Apotomo::Widget.helper method, which Cells gives us.
Processing the input
The :submit event is catched by the twitter widget. Remember how we set up the observer?
Right, we had that responds_to_event statement. It simply invokes #process_tweet.
To validate the input we have to change this processing state a bit.
Using #update_attributes we let the model handle the validation and saving (line 10-11).
After validating we re-render the main display view and send it back. This will redraw the (hopefully) updated tweets list and eventually show an error message.
Separation of Concerns?
When playing around with the current state of our widget you may notice that the entire tweets list is reloaded even when we want to display a validation error, only. Since we’re rendering display at the end of #process_tweet we instruct a total re-rendering.
This is not what we want.
Why not tear apart the complex twitter widget into a container and a form? We will learn just that in the next chapters.

