开发者

Obtaining a Nested Model's Count in the Controller

I have the following two models:

photoalbums
 has_many:photos

photos
 belongs_to:photoalbums
开发者_Go百科

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜