This is probably not the best way of doing it, as I’m rather new to Rails, but I thought I should still share since I was not able to find any information on the topic. Please post alternative solutions or improvements.
One way of getting validation with Rails and Ajax.InPlaceEditor, using the Rails validators, is outlined below. Similar methods could, of course, be used to validate model data with other applications of AJAX.
On the page with the editor, set onFailure to a function that does something (in this case, just an alert) with errors:
<%= javascript_tag %Q|
function ajax_error(transport) {
rawText = transport.responseText;
alert(rawText);
}
new Ajax.InPlaceEditor('field_id', '/items/ajax_update', {onFailure: function(t) { ajax_error(t) } });
| %>
Instead of plain text, this could be e.g. a JSON object (using the ruby-json gem with Rails):
function ajax_error(transport) {
rawText = transport.responseText;
json = eval('(' rawText ')');
do_something_with(json);
}
In the ajax_update action, if errors are encountered, output an error code such as “500 Internal error” and the error text, or—in this example—as a JSON object:
if @item.save
render :layout => false, :inline => "<= @value >"
else
@errors = @wish.errors.full_messages
render :layout => false, :inline => " <= @errors.to_json >", :status => 500
end
The 500 status will trigger onFailure, where you can do alerts or whatever you fancy.
—HenrikN
Another article on this subject can be found at http://www.bigsmoke.us/ajax-validation-on-rails/
—BigSmoke
You can read an alternate (and in my opinion more elegant) solution at:
The code there shows how to display ActiveRecord validation errors as nicely formatted Javascript Alerts, without requiring any external gems, etc.
—Ryan Norbauer
A hack that allows in_place_edit to use ActiveRecord validation and diplays error messages in Javascript alert box.
http://www.pluitsolutions.com/2007/03/20/custom-in_place_edit-with-validation/
—Herryanto Siatono
Another validation hack, this one displays AR errors on the page rather than an alert:
http://offtheline.net/2006/7/12/fun-with-in_place_editor
—Jason L