Reputation: 1712
I have this variable in my pdforms_controller
that is grouping all of the pdforms based on their group_id.
@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>]}
Right now I am just calling this in my view to display this information.
<%= @groups.each do |group| %>
<%-# do something -%>
<% end %>
How can I get each record out of this array and display that data in separate columns, bootstrap cards, or whatever other container I want to use? I have never used arrays to store data so excuse me if this is either blatantly obvious or a stupid question.
Upvotes: 0
Views: 57
Reputation: 54882
When you have a hash, like { key: 'value', other_key: 'other_value' }
, you can use each
as the following:
# 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"
So in your case, you can simply do:
@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
Upvotes: 1