views:

19

answers:

1

I have the following two models:

photoalbums
 has_many:photos

photos
 belongs_to:photoalbums

When I show a list of all the photoalbums, I want to also say how many photos exist in the album:

Controller:

def index
    @photoalbums = PhotoAlbum.all
end

View:

<%# Get the number of photos per this album %>
<% @photos = Photo.find_by_photo_album_id(photoalbum.id) %>
<li><%= @photos.count %> Photos</li>

The above isn't allowing me to do @photos.count or @photos.record in the view.

Is there a better way to do this in the controller? I thought about perhaps an include(:photos) in the controller?

Thanks!!!

+1  A: 

Solution 1) In your view you need to write this..

<% @photos = Photo.find_all_by_photo_album_id(photoalbum.id) %>
<li><%= @photos.count %> Photos</li>

instead of find_by_photo_album_id find_all_by_photo_album_id.

Solution 2)

In controller

def index
   @photoalbums = PhotoAlbum.find(:all,:include => :photos)
end

In View

<% @photos = photoalbum.photos %>
<li><%= @photos.count %> Photos</li>
krunal shah
Thanks but should I be doing some type of EAGER, include type thing in the controller for performance reasons? trying to learn that stuff?
AnApprentice
@TheApprentice I have edited my answer.
krunal shah