简体   繁体   English

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

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

I have a parent model that has many children:我有一个父母 model 有很多孩子:

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> .我收到一个错误,例如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.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 %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM