Reputation: 5382
There's a good number of related questions but their answers haven't helped me. I have a method fetch_all_sections
which populates an array with this line:
all_sections << {:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth}
In a loop in a view, I would like to easily access the values by their key, like this:
<% fetch_all_sections(@standard).each do |section| %>
<%= section.id %>
<% end %>
This says no method id on section. section[:id]
and #{section['id']}
have similarly themed errors. I used a hash for ease of retrieval - should I use a different structure?
I'm hoping I don't need .map like section.map { |id| id[:id] }
for every value.
EDIT: Here's the context. It's a little loopy (pun intended) but it does what's intended.
# Calls itself for each section recursively to fetch all possible children
def fetch_all_sections(standard, section = nil, depth = 0)
all_sections = []
if section.nil?
rootsections = standard.sections.sorted
if ! rootsections.nil?
rootsections.each_with_index do |section, i|
depth = section.sortlabel.split('.').length - 1
all_sections.push(fetch_all_sections(standard, section, depth))
end
end
else
all_sections << {:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth}
section.children.sorted.each do |section|
all_sections | fetch_all_sections(standard, section)
end
end
return all_sections
end
Upvotes: 0
Views: 138
Reputation: 54902
Try with the following:
<% fetch_all_sections(@standard).each do |section| %>
<%= section['id'] %>
<% end %>
If not working, try debugging using these methods:
<% fetch_all_sections(@standard).each do |section| %>
<%= section.inspect %>
<%= section.class %>
<% end %>
As the Question author said, this fixed:
all_sections << fetch_all_sections(standard, section, depth).first
And tell us the output of the inspect
Upvotes: 1