如何使用每种方法按类型分隔元素?

时间:2013-12-29 19:34:05

标签: ruby-on-rails ruby each

我创建了两个脚手架:announce_sections和公告。 announce_sections是公告的类型(即游戏,试用等),当我创建公告时,我指定它是什么类型的announce_sections。我正在尝试显示它,以便查看每个announce_section,每个公告及其信息在announce_section下。这就是我想出的:

  <% @announce_sections.each do |announce_section| %>
    <%= announce_section.name %>
    <% @announcements.each do |announcement| %>
      <%= announcement.announcement_title %>
      <%= announcement.information %>
      <%= announcement.additional_information %>
      <%= announcement.type %>
    <% end %>
  <% end %>

但是,此代码仅显示带有所有公告的announce_sections。公告不会分成各自的announce_sections。如何更改它呢?

2 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题,但一个简单的方法是构建一个哈希,其中键是announcement_section的类型,值是公告的数组(或Set)。构建该哈希的一种方法是使用构造函数的Hash.new {|hash, key| ... }形式。

@hash = Hash.new {|hash, section| hash[section] = Array.new }
@announcements.each do |a|
  # for each announcment append it to the array under the hash
  @hash[a.section] << a
end

然后,在视图中

<% @hash.keys.each do |section| %>
  <%= section %>
  <% @hash[section].each do |announcement| %>
    <%= announcement.announcement_title %>
    <%= announcement.information %>
    <%= announcement.additional_information %>
    <%= announcement.type %>         
  <% end %>
<% end %>

答案 1 :(得分:0)

<% @announce_sections.each do |announce_section| %>
  <%= announce_section.name %>
  <% @announcements.where(type: announce_section).each do |announcement| %>
      <%= announcement.announcement_title %>
      <%= announcement.information %>
      <%= announcement.additional_information %>
      <%= announcement.type %>
  <% end %>
<% end %>

使用您用于分配公告类型的字段名称而不是“类型”