在表中显示has_many关联的数据

时间:2013-06-06 23:47:15

标签: 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 :counties, dependent: :destroy
end

class County < ActiveRecord::Base
  attr_accessible :county_name, :district_id
  belongs_to :district
  has_many :subcounties, dependent: :destroy
end

我希望在表格中显示这些数据,以便我有三列Region,District和county。这样一个地区的所有地区和一个地区都覆盖了各自的县。

我尝试了类似的东西,但它没有用

    <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>

我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

您将遇到的一个问题是,您所描述的数据结构无法在 true 三列表中实现。相反,您需要创建一个两列父表,其中两个额外的列嵌套在父表的第二列中。不幸的是,这会导致您的表格标题略显偏差。

但是,如果您坚持使用表格布局,则以下内容应该完成类似于您要查看的内容:

<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>