从Rails数组中提取记录

时间:2017-12-21 16:58:28

标签: ruby-on-rails

我的pdforms_controller中有这个变量,它根据group_id对所有pdforms进行分组。

@groups = Pdform.where(principal_action: 'approved', super_action: 'new').group_by(&:group_id)


>      {"DSC-002"=>[#<Pdform id: 63, date_start: "2017-12-08", date_finish: "2017-12-09", location: "First test", mtg_name: "First
> test", memo: "First test", acct_num: "12312312323", sub: true,
> accepted: false, guest_id: nil, created_at: "2017-12-08 21:36:37",
> updated_at: "2017-12-21 15:43:57", user_id: 13, pdtype:
> "instructional", reason: nil, prr_requested: nil, length: "full",
> principal_action: "approved", super_action: "new", group_id:
> "DSC-002", is_group: false>], 
>         "DSC-001"=>[#<Pdform id: 64, date_start: "2017-12-19", date_finish: "2017-12-20", location: "test", mtg_name: "test", memo:
> "test", acct_num: nil, sub: false, accepted: false, guest_id: nil,
> created_at: "2017-12-19 14:37:48", updated_at: "2017-12-20 18:05:55",
> user_id: 13, pdtype: "instructional", reason: "Dont like\r\n",
> prr_requested: nil, length: "half", principal_action: "approved",
> super_action: "new", group_id: "DSC-001", is_group: false>, #<Pdform
> id: 65, date_start: "2017-12-19", date_finish: "2017-12-20", location:
> "group test", mtg_name: "group test", memo: "group test", acct_num:
> "", sub: false, accepted: false, guest_id: nil, created_at:
> "2017-12-19 20:20:02", updated_at: "2017-12-21 15:50:21", user_id: 13,
> pdtype: "technology", reason: "wait, huh?", prr_requested: nil,
> length: "half", principal_action: "approved", super_action: "new",
> group_id: "DSC-001", is_group: false>]}

现在我只是在我的视图中调用此信息来显示此信息。

<%= @groups.each do |group| %>
  <%-# do something -%>
<% end %>

如何从该阵列中获取每条记录并在单独的列,引导卡或我想要使用的任何其他容器中显示该数据?我从来没有使用数组来存储数据,所以请原谅我,如果这显然是明显的或是一个愚蠢的问题。

1 个答案:

答案 0 :(得分:1)

如果您有哈希,例如{ key: 'value', other_key: 'other_value' },则可以使用each作为以下内容:

# in rails console
h = { some_key: 'value', other_key: 'other_value' }
h.each do |k, v|
  puts "the value for key #{k.inspect} is #{v.inspect}"
end
# it will output:
the value for key :some_key is "value"
the value for key :other_key is "other_value"

所以在你的情况下,你可以做到:

@groups.each do |group_id, pdforms|
  # group_id is the key (ex: "DSC-002")
  # pdforms is the value for that key (in your case: an array of Pdform records)

  # in this loop you can then cycle through all `pdforms`:
  pdforms.each do |pdform|
    # do something with a single Pdform record
  end
end