你可能想引入一個層次到您的數據對象。 這可以通過幾種方法完成。如果你想硬編碼的東西看看the ancestry gem
:
# locations_controller.rb
def index
@locations = State.all
end
# app/views/locations/index.html.erb
<ul>
<%= render @locations %>
</ul>
# app/views/locations/_state.html.erb
<li>
<%= state.name %>
<% if state.provinces.present? %>
<ul>
<%= render state.provinces %>
</ul>
<% end %>
</li>
# app/views/locations/_province.html.erb
<li>
<%= province.name %>
<% if province.districts.present? %>
<ul>
<%= render province.districts %>
</ul>
<% end %>
</li>
# app/views/locations/_district.html.erb
<li>
<%= district.name %>
<% if district.cities.present? %>
<ul>
<%= render district.cities %>
</ul>
<% end %>
</li>
# app/views/locations/_city.html.erb
<li>
<%= city.name %>
</li>
對於你需要引入一個祖先方法爲每個模型麪包屑。例如
class City
...
def ancestry
district.ancestry << self
end
...
end
# ... other classes
class State
...
def ancestry
[self]
end
end
然後你就可以呈現麪包屑部分
# app/views/layout.html.erb
<%= render partial: 'shared/breadcrumbs', locals: { ancestry: @some_instance.
def breadcrumbs(ancestry)
ancestry
end
# app/views/shared/_breadcrumbs.html.erb
<ul>
<% ancestry.each do |location| %>
<li>
<%= link_to location.name, url_for(location) %>
</li>
<% end %>
</ul>
我是儘量協會所有model.Added外鍵關聯表的表,我home.html.erb如何顯示樹形視圖? –