Ruby on Rails:如何获取和显示后代记录?

时间:2011-07-05 20:45:03

标签: ruby-on-rails

我有一个有很多孩子的父模型:

class Band < ActiveRecord::Base
  has_many :concerts
end

class Concerts < ActiveRecord::Base
  belongs_to :band
end

现在我想在索引视图中显示它们,但我无法弄清楚显示子记录的语法:

<% @bands.each do |band| %>
  Band name: <%= band.name %>
  Concerts:
  <ul>
    <% @bands.concerts.each do |concert| %>
      <%= concert.location %>
    <% end %>
  </ul>
<% end %>

我收到类似undefined method 'concerts' for #<Array:0x00000102c537f0>的错误。获取和显示后代模型的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您非常接近,但您需要将@bands.concerts.each更改为band.concerts.each

<% @bands.each do |band| %>
  Band name: <%= band.name %>
  Concerts:
  <ul>
    <% band.concerts.each do |concert| %>
      <%= concert.location %>
    <% end %>
  </ul>
<% end %>