has_one |嵌套属性 -

时间:2010-03-15 16:05:01

标签: ruby-on-rails nested nested-attributes

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

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

这就是我所拥有的。我只想为每张专辑展示封面。

任何关于此的信息都将是一个巨大的帮助!

1 个答案:

答案 0 :(得分:2)

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

<% @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"

OR

@albums = Album.all :include => [:photos], :order => "name ASC"
相关问题