Wasswa Samuel
Wasswa Samuel

Reputation: 2179

Displaying data with has_many association in a table

I have three models like this

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

I want display this data in a table such that i have three columns Region,District and county. Such that a region is diplayed with all its districts and a district with all its counties in their respective columns.

I tried something like this but it didn't work

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

How would i do this correctly?

Upvotes: 0

Views: 104

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

One issue you're going to run into is that the data structure you've depicted can't be implemented in a true three column table. Rather, you'll need to create a two column parent table where two additional columns are nested within the second column of the parent table. Unfortunately, this will cause your table headers to look a bit off.

However, if you're insistent upon using a table layout, the following should accomplish something akin to what you're looking to do:

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

Upvotes: 1

Related Questions