Display Validation Errors For Your Ajaxified Form
One of the sweet things Rails provides is practically free error notification on forms. With just a little bit ofvalidations on your model, and some logic in your controller, bam, instant error messaging. Very simple. But what if your form is using AJAX to post? The page doesn't re-render, so how is our buddy,
error_messages_for, going to work? Well its not, we're gonna have to use AJAX to display the errors. It turns out this isn't too touch, but as usual we want to keep it DRY. h2. The Controller
We will attempt to create the Post. If all goes well, then the create rjs action will fire and all is well. But if the record fails validation, we catch it, assign the current model to
@model, and render shared/validaiton_error.rjs.erb. This is our generic AJAX action for rendering errors for Models.
Create shared/validation_error.rjs and use this little snippit, and thats pretty much it for this part.
divin the page. Let's go add this fancy
div. h2. The View This part is pretty simple. You just need to open up your form partial, _posts/_form.html.erb_ and add this little view helper to the form:
This does nothing but prints out a
div with a specific ID to prepare for our RJS action, if it’s needed. So let’s go make the view helper.
Now we can just call this simple view helper and pass in any model and it will dynamically build a div with the appropriate ID inside.
And thats pretty much it. To go through it again, when the form is loaded, the error div will be placed in the page, waiting to be used. Once the form is submitted in the background, the controller’s create action will attempt to save it. If the record is invalid with validation errors, then the universal validation_errror RJS template will be fired off and replace all the errors from the failed validation, into the div we placed in the page. Oh and of course a little red flash action to make sure the user sees the errors.