索引多关系多态

时间:2012-11-14 00:43:46

标签: ruby-on-rails ruby ruby-on-rails-3

我想知道是否有可能做到以下

我有很多文章,而且 我有很多照片。

我正在尝试展示所有文章以及属于该文章的所有照片集。对我在控制器中我想做以下

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

2 个答案:

答案 0 :(得分:2)

所以你有一套articles。出于某种原因你使用Article.all[1..-1]所以我会坚持下去 那么您希望每个photos的{​​{1}}合并为一组articles吗?

由于您使用photos,因此可以使用flat_map

Rails

答案 1 :(得分: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>