Search code examples
ruby-on-railsrubypartialrenderpartial

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\<%= point.id %>.gif" />
    <%= link_to_remote "&nbsp;&nbsp;&nbsp;Delete", :url => { :action => "delete_point", :id => point.id  }, :before => "Element.show('spinner')",  :complete => "Element.hide('spinner')" %>        
</div>
<% 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.


Solution

  • 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 %>