【问题标题】:Association all model in ruby on rails在 ruby​​ on rails 中关联所有模型
【发布时间】:2014-07-16 08:37:26
【问题描述】:

我是 ruby​​ on rails 的新手,我要创建在线租赁系统。

这是位置基础模型

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

【问题讨论】:

  • 我正在尝试关联所有模型。为相关表添加外键,我的 home.html.erb 如何显示树视图?

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1


【解决方案1】:

您可能希望在数据对象中引入层次结构。 这可以通过几种方式完成。看看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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多