#75 Complex Forms Part 3

In this third and final episode on complex forms I will show you how to edit a project and multiple tasks all in one form. This includes removing and adding tasks dynamically as well. See the show notes for updated code.

Update (3/29/2008): The code for this screencast isn't the greatest, it requires the :index option for the fields and does not work well in Rails 2. Instead I recommend going with the approach I show in Advanced Rails Recipes Here's the code (posted by permission). Check out the recipe for details on how it works.

Validation

Displaying the validation errors can be tricky depending on your needs. It may be as simple as displaying the project validations:

projects/_fields.rhtml

<%= error_messages_for :project%>

This will mention if there are task validation errors, however it will not state exactly what the errors are because these are stored in each task model.

If you need to display the task error messages. One way is to do this:

projects/_task.rhtml

<%@task = task %><%= error_messages_for :task%>

The error_messages_for method requires an instance variable with the same name, so that is why it needs to be set right there. This is an ugly work around. If you want to do it in a cleaner way or handle the error messages differently then I recommend creating your own validation helper method instead. I may go into more details in a future episode.

If you want to share your validation troubles feel free to add a comment!