2012-11-14 18 views
0

多重關係我想知道,如果可以做到以下指數多態性

我有許多文章和 我有許多照片。

我想顯示屬於文章的所有文章和所有照片集。對我來說,在控制器中我想做以下的事情

@mosttop = Article.all[1..-1] 
@loc = @mosttop.photos 
+0

'顯示所有文章和所有的一套屬於article' <=這是沒有意義的照片。如果您擁有所有文章,那麼「文章」是什麼? – oldergod

+0

好吧,我想顯示所有文章,如索引行動會。在我的情況下,我實際上使用mosttop = Article.all [1 ..- 1],所以它不是全部。然後,我想通過合併@ mosttop.photos來查看索引文件夾中的所有圖片,其中關聯的 – Jseb

回答

2

所以你有一套articles。由於某種原因你使用Article.all[1..-1],所以我會堅持下去。
然後你想每個photos的每個articles合併成一組photos

由於您使用Rails,您可以使用flat_map

@articles = Article.all[1..-1] 
@photos = @articles.flat_map(&:photos) 

@photos.each do |photo| 
    # show photo 
end 
+0

使用'flat_map'方法會導致N + 1個SQL查詢。 –

+0

謝謝指出。 http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations – oldergod

1
# app/models/article.rb 
has_many :photos 

# app/models/photo.rb 
belongs_to :article 

# app/controllers/article_controller.rb 
def index 
    @articles = Article.include(:photos).all 
end 

# app/views/articles/index.html.erb 
<%= render :partial => "articles/article_with_photos", :collection => @articles 

# app/views/articles/_article_with_phots.html.erb 
<H2><%= article.title %></H2> 
Photos 
<ul> 
    <% article.photos.each do |photo| %> 
    <li><%= image_tag(photo.url) %></li> 
    <% end %> 
</ul>