slotishtype slotishtype - 1 year ago 84
Ruby Question

Rails rendering a partial multiple times based on the collection size

I have a partial that takes a collection, iterates through that collection displaying the individual items.

Here is the code:

The Partial:

<% for point in @points %>
<div id="im" style="float:left;width:80px;height:90px;padding:5px;border:solid 1px #D3D3D3; margin:5px; ">
<img width="80" height="80" src="\uploaded\<%= %>.gif" />
<%= link_to_remote "&nbsp;&nbsp;&nbsp;Delete", :url => { :action => "delete_point", :id => }, :before => "'spinner')", :complete => "Element.hide('spinner')" %>
<% end %>

The rjs from the controller:

page.replace_html :points_partial, :partial => 'points', :collection=>@points

For some reason the partial is rendered by the amount of items in the collection. If there are ten items in the collection then the partial is rendered then times.

This guy had a similar problem but it was related to layouts.

Render partial in Ruby on rails a collection is multiplying items

It is driving me mad because it should be simple and all the other partials work without any difficulty.

Answer Source

The :collection causes the controller to iterate over @points and render the partial once for each item in the collection. If you set up the partial to render just one point, the controller code should work as expected.

BTW, in Rails 3 you can use <%= render @points %> as a shortcut for <%= render :partial => "points/point", :collection => @points %>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download