开发者

Ruby on Rails: How to fetch and display descendent records?

I have a parent model that has many children:

class Band < ActiveRecord::Base
  has_many :concerts
end

class Concerts < ActiveRecord::Base
  belongs_to :band
end

Now I would like to display them in my index view, but I can't figure out the syntax for displaying the children records:

<% @bands.each do |band| %>
  Band name: <%= band.name %>
  Concerts:
  <ul>
    <% @bands.concerts.each do |concert| %>
      开发者_开发技巧<%= concert.location %>
    <% end %>
  </ul>
<% end %>

I'm getting an error like undefined method 'concerts' for #<Array:0x00000102c537f0>. What is the proper way for fetching and displaying the descendent models?


You were really close, but you need to change @bands.concerts.each to band.concerts.each.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜