Cristian Livadaru's blog

... think again ...

AJAX Validation on Rails

I had a ajax form to add languages in the system in one of my projects. A pretty simple form with just one text field. The problem I had was with validations and display the error message if something goes wrong.
After search the net for a while I came across this blog from bigsmoke which could solve my issues, but after looking a bit it kind of looks a bit complicated and I wanted something more simple.
I took some ideas from bigsmokeand did my own thing.

So here is my implementation of Ajax validation on Rails:

My controller has a “new” action which looks like this

def new
  @language = Language.new(params[:language])
  if @language.save
    @language.reload
    return if request.xhr?
  else
    render :partial => 'error', :status => 444
  end
end

The view where the languages are displayed I have added a hidden div which will display the error message if present

Here is where the most stuff happens, in the _error.rjs

page.replace_html 'errors', "Language could not be created. Reason: #{@language.errors.full_messages}"
page.delay(5) do
  page.visual_effect :fade, 'errors'
end
page["errors"].toggle

This replaces the errors div with a message and the errors returned from the validation, it starts a fade with a delay so that the error message will disappear after a while and finally, the div is set to visible.

That’s it! It really is that simple.