slotishtype
slotishtype

Reputation: 2751

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.

Upvotes: 2

Views: 3327

Answers (2)

weltraumpirat
weltraumpirat

Reputation: 22604

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

Upvotes: 4

Dylan Markow
Dylan Markow

Reputation: 124419

the :collection parameter is telling the partial "display the partial for each member of @points", and then your partial iterates again through the same collection.

In your partial, just get rid of the wrapping for point in @points loop and it should work fine.

See here for more info: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-collections

Upvotes: 2

Related Questions