从Rails数组中提取记录

问题描述 投票:0回答:1

我在我的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 %>

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

ruby-on-rails
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.