0

Iam新的紅寶石在軌道上,我要創建在線租賃系統。協會紅寶石在軌道上的所有模型

這是外景基地模型

app/models/state.rb 
Class State < ActiveRecord::Base 
has_many :provinces 
end 

app/models/province.rb 
Class Province < ActiveRecord::Base 
belongs_to :state 
has_many :districts 
end 

app/models/district.rb 
Class District < ActiveRecord::Base 
belongs_to :province 
has_many :cities 
end 

app/models/city.rb 
Class City < ActiveRecord::Base 
belongs_to :district 
end 

首先的問題是如何能像下面

  • 顯示所有阿拉斯加
  • 加州
    • 洛杉磯
    • 弗雷斯諾
      • Cincotta(弗雷斯諾)
      • 哈蒙德(弗雷斯諾)
      • 梅爾文(弗雷斯諾)
        • 梅爾文1
        • 梅爾文2
  • 亞利桑那
  • 科羅拉多

第二個問題是,如何創建麪包屑的所有模型

加州弗雷斯諾>> >> >>梅爾文梅爾文1

+0

我是儘量協會所有model.Added外鍵關聯表的表,我home.html.erb如何顯示樹形視圖? –

回答

0

你可能想引入一個層次到您的數據對象。 這可以通過幾種方法完成。如果你想硬編碼的東西看看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> 
+0

謝謝,我在我的應用程序中添加了祖先的寶石。 –

+0

添加新問題http://stackoverflow.com/questions/24787750/creating-has-many-association-with-ancestry-gem請讓我幫忙 –