When you start using Rails you pretty soon start using partials for saving forms in an extra template in order to re-use them in the different views of a CRUD interface.
If you go just a little bit further you’ll find out that partials are also very useful when building Ajax applications with Rails. Often when you do an Ajax call the one thing you want to do in the callback is updating the DOM of the page.

When the user clicks on the plus-button in above user interface, a form will popup which allows him to add another list. Once the form is filled in it will be send to the server using an Ajax call. Finally in the callback the new list will be added to the DOM.
So there are two situations when you want to render a list:
- When the page with all available lists is rendered.
- When the user adds a new list.
This sounds like the perfect use-case for a partial, so let’s create one. For above user interface the ERB template could look like this:
1 2 3 4 5 6 7 8 9 10 | <li id="list_<%=list.id%>" class="list"> <div> <h1><%= list.title == '' ? '<em>enter a title</em>' : list.title %></h1> <div class="summary"> <%= pluralize list.list_items.length, 'item' %> , <%= pluralize list.list_items_done, 'item' %> done.<br/> Last updated <%= distance_of_time_in_words list.updated_at, Time.now %> ago </div> </div> </li> |
We save this code in a file named _list.html.erb.
In the view which generates the complete list of lists, we call the partial from within an each loop (index.html.erb):
1 2 3 | <%- @lists.each do |list| -%> <%= render :partial => 'lists/list', :object => list %> <%- end -%> |
If you look back to the partial code in _list.html.erb, you’ll notice a local variable being used called list. By adding the parameter :object => list to the render call in index.html.erb we make this variable available in the partial.
Let’s finally have a look at the view for the Ajax callback. It’s saved in create.js.erb and can be as easy as this:
1 2 | var new_list = "<%=escape_javascript(render :partial => 'lists/list', :object => @list)%>"; $("#all_lists").prepend(new_list); |
All we do is assigning the list-HTML to a Javascript variable. For this we need to wrap the render call into an escape_javascript. Next we prepend this list to the ul-element using jQuery. That’s it.
Even though this is not a complete code example I hope it’ll point into the right direction. Please post questions as comments to this post.
I'm a Software Developer, currently working at 
0 responses so far ↓
There are no comments yet...Kick things off by filling out the form below.
Leave a Comment