AJAX validation on Rails

Written by BigSmoke on March, the 28th, in 2006

This text discusses how I handled validation messages and other notices caused by AJAX requests in Rails.

Update – 20 april 2007: Wiebe fixed a long-standing bug in the code: non-AJAX flash messages were not being discarded at all, resulting in them remaining in the flash a request too long.

Update – 20 may 2006: Wiebe pointed out to me that the FIXME comment in the application controller snippet was very unclear. This is now fixed. He also wanted to remind the unsuspicious reader that the json gem doesn't necessarily need to go into the vendor directory; it could also be installed globally, which is, incidentally, exactly what we did before freezing it.

The problem

I wanted AJAX requests in Rails to result in error handling and message reporting that was at least as nice (and almost as easy) as doing the same thing without AJAX.

A solution

Let me start with a short summary of the steps I followed to get easy, transparent error handling for AJAX requests.

  1. Make validation errors cause a 4xx HTTP error.
  2. Store validation error messages within the flash.
  3. Pass the flash to the browser through the X-JSON header.
  4. Extract the validation error messages and other flash notices from the X-JSON header using a custom AJAX responder.

Making validation errors cause a 4xx HTTP error
and handling action failures in the views

First, I needed to distinguish between actions that fail and actions that succeed. Rails makes this as easy as can be:

n0 V\& U)mPװ˜ȥs(vAYB|W sV4ua'YJ97$7 :o!m(lhmYń$The above form will update the comment element on success and the comment_edit element on failure.

Now, I needed to organize the update action so that it does the right thing on success and on failure.

]n0 9$U藐80ƅHiR%)/0 6Jvڌfs$`QbFJ\ V֬?s6t:v⍖ܛs,%`UB v;*>*KxQDM4IabBĂ~||EwV9#6C۩fQx=lh 8AX G~+vc٦(>A28]fޛ,Q6R5ЕMaT ~"`%؝>[~C=P{&-Y`m%\?+m&ȅ ^ ƶ"/%.it

(I use success and failure in the flash to better be able to distinguish between different types of messages when adding pretty icons and colors in the CSS stylesheets.)

The most important part here is rendering the edit partial with a 444 status code. This 444 code will make the request fail, which is just what I needed to rerender the form with invalid fields marked as such. This marking is done automatically by Rails.

Next, I wanted to override Rails' default behaviour because, by default, ActionController surrounds each invalid field with a <div class="fieldWithErrors"> element. This wouldn't be too bad if it were a span (<div>s in the wrong places will wreak havoc in many otherwise valid pages), but I rather have the classes added to the actual fields. This was done by adding the following code to environment.rb. (See ticket #2210 for more information on Rails' faulty default.)

TN0)Q:5K x"]&%m-ՐlӋ^|9M[IR,!dRpFp%&icMd$"WSs &dҍc jNrO''tъ(Jz'tB=I=. ΢x\ r5ʕ.9&գK&oV*beاe(&cC 6mBgcBn ?n+rKZFc#Z)JF+L)rަgؓ>+. Nn݉O˴5

Passing the flash to the browser through the X-JSON header

In my application.rb controller file, I added the following.

=k0ÆdJP0oڡK7اXEչB_%KL};P1Vqk췇;(,#AeI[̣=dq&I]pLQzmIu>~#T0(r'I>jH)4w\84/ Ònz-MrYC1VV?=Zw?-` 7!xi׹s즢% c=.ttz~{}YW< (ӻqm`euҶt'A}ALk_˷F

The flash_to_json_header after filter converts the flash to a JSON string which is added to the X-JSON header. The X-JSON header has a special meaning to Prototype.

To get the to_json method which I needed, I had to include the following lines in my environment.rb (after installing the appropriate gem in the vendor directory).

102TƸ%ع$%>Vڙ֯ *$2h⮕awũeuJk:f۶zȕgqVq63x{hAE([/1EqTx[/US2

Handling the X-JSON header

Now, I had to tell Prototype to actually do something with the JSON header. The following code does that (and a little useless bit more).

Note that as of this writing (2006-03-28), Prototype has a nasty JSON parsing bug where it doesn't surround the JSON to parse with parentheses. See the trouble ticket to check if my patch has already been accepted. If it hasn't, apply it yourself.

Ymo0_aUTڦcC)L,R׹w٦-~M@lSD|{9"Ju{4Rz̠넂* _¾v3f&xGtSڮgT 8a@x' -CgHKU"yWFQ\Q8-Te N [ y7쐧Q+[KLH_Wvn3PȪw@*a=Vw#dT?g; fҬ' BV'K%Z=1n4}ߜn(-)WJK͖:pTy:]Ѣy×The extractMessages(json) function is the function which does the actual work. The rest of the code in Messages is very custom and most probably of little interest to most readers.

In standard.rhtml layout file, I included the following code.

5M0 Y i+QTr;=Ӎ[E.W(liFM7-WcE҂sn1Xch˃;/'#O֚fY̕K̔>Z

Handling messages for non-AJAX requests

Note that to avoid complete dependency on JavaScript, I should have put a helper in <ul id="messages"> which simply outputs the messages through Ruby. Instead, because JavaScript independence was no requirement for this Intranet application, I used a helper—js_extract_messages_from_flash—which is defined as part of the ApplicationHelper module as follows:

RIn0_F"*K&9`&쟶k( "5XgG)amL<8(BwB;m{INM8J;;8OYgre#%Ʀ 0m6-nWOJW-"QI7v9DɮjKw sx@OuXS2 L#xbݍ'A icu/3gTfQ?6&_w`\U(p>)g

On 5 May 2006, John Collins has spoken a few nice words about this article. Thanks for that, John!

Discuss this story on digg.com.