2010-10-23 46 views
1

我有以下兩種模式:獲得一個嵌套模式的伯爵在控制器

photoalbums 
has_many:photos 

photos 
belongs_to:photoalbums 

當我告訴所有的photoalbums的名單,我想也說有多少張照片在相冊中存在:

控制器:

def index 
    @photoalbums = PhotoAlbum.all 
end 

查看:

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

以上不允許我在視圖中做@photos.count@photos.record

有沒有更好的方法在控制器中做到這一點?我想在控制器中可能是include(:photos)

謝謝!

+0

你說的 「不容許」 是什麼意思?如果你去腳本/控制檯並輸入相同的東西,@photos的價值是多少?你爲什麼不使用photoalbum.photos.count? – 2010-10-23 06:05:09

回答

2

解決方法1)在你看來,你需要寫這個..

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

,而不是find_by_photo_album_id find_all_by_photo_album_id。

方案二)

In controller 

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

In View 

<% @photos = photoalbum.photos %> 
<li><%= @photos.count %> Photos</li> 
+0

謝謝,但我應該做一些類型的EAGER,包括類型的東西在控制器出於性能原因?試圖學習這些東西? – AnApprentice 2010-10-23 06:16:28

+1

@TheApprentice我編輯了我的答案。 – 2010-10-23 06:18:17