Hi all,
Beginner’s question here: I’ve wondered, why I can’t browse through
“nested” models (belongs_to/has_many).
My models: (http://gist.github.com/291956)
class Enterprise < ActiveRecord::Base
has_many :branches
has_many :people, :through => :branches
end
class Branch < ActiveRecord::Base
has_many :people
belongs_to :enterprise
end
class Person < ActiveRecord::Base
belongs_to :branch, :include => :enterprise
end
And finally viewing people: (index.html.erb · GitHub)
Listing people
<% @enterprises.each do |ent| %>
<% ent.branches.each do |branch| %>
<% branch.people.each do |person| %>
<tr>
<td><%=h person.first_name %></td>
<td><%=h person.last_name %></td>
<td><%=h person.sex %></td>
<td><%=h person.age %></td>
<td><%=h person.email %></td>
<td><%= link_to 'Show', person %></td>
<td><%= link_to 'Edit', edit_person_path(person) %></td>
<td><%= link_to 'Destroy', person, :confirm => 'Are you
sure?', :method => :delete %>
<% end %>
<% end %>
<% end %>
<%= ent.name %> | ||||
---|---|---|---|---|
<%= branch.name %> (<%= branch.people.count %>)</ th> |
||||
First name | Last name | Sex | Age |
<%= link_to ‘New person’, new_person_path %>