0

インデックス ビューに多数のネストされたオブジェクトの 1 つを表示する方法

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

ビューで、ネストされたデータを反復処理します。すなわち

<% @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フィールドを使用している場合を除く)。:coverWHERE

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 に答える