Reputation: 12224
This is a Rails 3 project using jQuery 1.4.4.
I have an index action that displays a list of resources in a table, complete with a "Destroy" link like you'd get from a scaffold:
<tr id="showcase_item_<%= showcase_item.id %>" class="<%= cycle(' alt','') %>">
<td><%= displayable.identifier %></td>
<td><%= escape_javascript(link_to 'Remove', showcase_item, :confirm => 'Remove this item from your Showcase?', :method => :delete, :remote => true) %></td>
</tr>
On that index view I also have a little form that does an AJAX "create" for the resource, and I am using Javascript to append the resource to the table in my create.js.erb:
$("#showcase tr:last").after("<tr id=\"showcase_item_<%= @showcase_item.id %>\" class=\"<%= cycle(' alt','') %>\"> \
<% displayable = @showcase_item.displayable %> \
<td><%= displayable.identifier %></td> \
<td><%= link_to 'Remove', @showcase_item, :confirm => 'Remove this item from your Showcase?', :method => :delete, :remote => true %></td></tr>")
That is brittle, hideous, and not DRY. How else can I do that?
What is the Rails Way of doing this?
I appreciate any help or guidance you can provide!
Upvotes: 4
Views: 2438
Reputation: 11
I found this will work with erb
_create.js.erb
$('#objects').append("<%= escape_javascript(render :partial => @object) %>");
Upvotes: 0
Reputation: 11
I think Kevin have a small typo in his example. There should be used 'object' variable instead of '@object'
# _object.html.erb
<%= content_tag_for(:tr, object, :class => cycle('odd','even')) do %>
<td><%=h @object.name %></td>
...
Upvotes: 1
Reputation: 38032
The trick is to extract the table row into a partial (as it is being used twice). Then in your js
view, simple render the partial. For example, here is a small snippet to get you started:
# _object.html.erb
<%= content_tag_for(:tr, @object, :class => cycle('odd','even')) do %>
<td><%=h @object.name %></td>
<td><%= link_to 'Remove', object_path(@object), :method => :delete %></td>
<% end %>
# index.html.erb
<table id="objects">
<%= render :partial => @objects %>
</table>
# create.js.rjs
page << "$('#objects').append('#{escape_javascript(render :partial => @object)}');"
Upvotes: 4