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请让我帮忙 –