Simple question about collections

Alright, so… Let’s try this:

  1. I have a view which one way or another calls a controller action and
    wants to update a div.

  2. This controller action finds a collection of records and does a
    render :partial with said collection
    (e.g. : @patients with Patient.last and Patient.first)

  3. … What’s the partial going to look like? This is where I don’t
    understand how to use collections.

If I do a ":collection => " call, what exactly am I asking Rails to do…
And then how do I help it do that?

If I do a ":collection => " call, what exactly am I asking Rails to do…

You are enabling a local variable in your partial with the same name
as the partial. The variable name will be singular and will be
initialized to each of the values that :collection contains.

Here’s an example:


from: photos_controller.rb

def index
@photos = Photo.paginate(:page => params[:page],
:conditions => ‘thumbnail IS NULL’,
:order => ‘created_at’,
:per_page => 9
)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @photos.to_xml }
end
end


from: views/photos/index.html.erb

All Photos

<% params[:fromURL] = photos_path() %>

<%= will_paginate @photos %>

    <%= render :partial => 'photo', :collection => @photos %>

<%= will_paginate @photos %>


from: views/photos/_photo.html.erb

  • <%= link_to image_tag(photo.public_filename('thumb')), photo_path(:id => photo) %>
  • This sequence has the result of presenting a paginated view with nine
    thumbnails, each of which is linked to the full sized image it
    thumbs. The pagination will allow for the presentation of all
    thumbnails in the collection.

    So the sequence is:

    1. controller identifies complete collection as paginated and passes
      in to view as @photos
    2. view deals with pagination action of :per_page photos and passes
      each photo in turn to the partial
    3. partial presents each photo as its’ thumbnail linked to its’ full
      sized variant

    This is just one of several ways to use partials but I think you
    should be able to understand. One big gain here is the absence of the
    for loop needed to do the nine thumbnails. The other is the ability
    to call the partial from another controller/view sequence, i.e. here
    we’re stepping through all the photos in the library by, as the photo
    model is associated with a user model, we can also use the partial to
    view all the photos owned by a specific user.

    I see. Thank you!