Ruby on rails 在一个表中显示具有多个关联的数据

Ruby on rails 在一个表中显示具有多个关联的数据,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,我有三个这样的模型 class Region < ActiveRecord::Base attr_accessible :region_name has_many :districts, dependent: :destroy end class District < ActiveRecord::Base attr_accessible :district_name, :region_id belongs_to :region has_many :countie

我有三个这样的模型

class Region < ActiveRecord::Base
  attr_accessible :region_name
  has_many :districts, dependent: :destroy
end

class District < ActiveRecord::Base
  attr_accessible :district_name, :region_id
  belongs_to :region
  has_many :counties, dependent: :destroy
end

class County < ActiveRecord::Base
  attr_accessible :county_name, :district_id
  belongs_to :district
  has_many :subcounties, dependent: :destroy
end
类区域
我想在一个表格中显示这些数据,这样我就有三列:地区、地区和县。这样,一个区域的所有区域和一个区域的所有县都显示在各自的列中

我试过这样的东西,但没用

    <table>
    <tr> 
    <th>Region</th>
    <th>District</th>
    <th>County</th>
    </tr>
    <% @regions.each do |region|%>
    <tr>
    <td><%=region.region_name%></td>
     <td><%=region.districts%></td>
     <td><%=region.districts.counties%></td>
    </tr>

    <%end%>
    </table>

区域
地区
县

如何正确执行此操作?

您将遇到的一个问题是,您所描述的数据结构无法在真正的三列表中实现。相反,您需要创建一个双列父表,其中两个附加列嵌套在父表的第二列中。不幸的是,这将导致您的表标题看起来有点不对劲

但是,如果您坚持使用表布局,则以下内容应能完成与您所期望的类似的工作:

<table>
    <tr> 
        <th>Region</th>
        <th>District/County</th>
    </tr>
    <% @regions.each do |region|%>
    <tr>
        <td><%=region.region_name%></td>
        <td>
            <table>
            <% region.districts.each do |district| %>
                <tr>
                    <td><%= district.district_name %></td>
                    <td>
                        <table>
                        <% district.counties.each do |county| %>
                            <tr>
                                <td><%= county.county_name %></td>
                            </tr>
                        <% end %>
                        </table>
                    </td>
                </tr>
            <% end %>
            </table>
        </td>
    </tr>
    <% end %>
</table>

区域
区县

我认为最好在列表中设置格式
ul li
这有什么不起作用?如何正确格式化数据。也许有更好的方法,这些方法只是返回数据的散列。