0

如何在索引视图中显示许多嵌套对象之一

class Album < ActiveRecord::Base 

has_many: photos
accepts_nested_attributes_for :photos,
 :reject_if => proc { |a| a.all? { |k, v| v.blank?} }


has_one: cover
accepts_nested_attributes_for :cover


end

class Album Controller < ApplicationController
  layout "mini"
  def index
    @albums = Album.find(:all,
    :include => [:cover,]).reverse

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @albums }
    end
  end

这就是我的票价。我只想为每张专辑展示一个封面。

任何关于这方面的信息都会有很大的帮助!!

4

1 回答 1

2

在您的视图中迭代嵌套数据。IE

<% @albums.each do |album| %>

  <%= album.name %>
  <% # display other album details %>

  <%= image_tag album.cover.name %>

  <% album.photos.each do |photo| %>
    <%= image_tag photo.name %>
  <% end %>
<% end %>

在您的控制器中包括photos在查询结果中。

@albums = Album.all :include => [:photos]

您不需要:cover在查询中包含 ,因为它是一个has_one关联(除非您使用条件:cover中的字段WHERE)。

我怀疑您正在reverse调用对结果集进行排序。请改用该:order子句。

@albums = Album.all :include => [:photos], :order => "created_at ASC"

或者

@albums = Album.all :include => [:photos], :order => "name ASC"
于 2010-03-15T16:26:41.513 回答