Thursday, August 7, 2014

Rails ajax render template

When working Rails Ajax queries, I commonly need to update more than one section of a page. For instance, a submit action might update a data table, but may also need to show some notifications in #messages. I've collected a few techniques that I've found posted in various forums and blogs into this solution that I use.

One important thing to note is that Rails is much friendlier with form submissions with remote: true than it is with $.ajax() calls. ActiveRecord models tie gracefully with the form_for tag, but sometimes link_to tags are used with anchors (links).

The first thing to use is the remote: true form option which sets the html data-remote attribute. Secondly, set a custom data-update-target attribute which specifies which div to replace with the body of the rendered ajax layout.

The shared messages template is used by both the main application layout and the ajax layout to provide updated notices on ajax actions.

Here is the ajax layout template rendered for the response:

And here is the javascript that extracts the #messages div replacing the notices, and replacing the data-update-target div:

Finally, in the controller, set the ajax layout for the action.