0
有很多相关的问题,但他们的答案并没有帮助我。我有一个方法fetch_all_sections
,其填充有此线的数组:Rails:从数组中检索哈希值
all_sections << {:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth}
在一个视图中的循环,我想容易地通过他们的密钥访问值,如下所示:
<% fetch_all_sections(@standard).each do |section| %>
<%= section.id %>
<% end %>
这在部分上说没有方法ID。 section[:id]
和#{section['id']}
也有类似的主题错误。为了便于检索,我使用了散列 - 我应该使用不同的结构吗?
我希望我不需要.map像section.map { |id| id[:id] }
为每个值。
编辑:这是上下文。这是一个有点loopy(双关语意),但它确实是有意的。
# 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
确实似乎我已经制作了一个具有1个散列的数组,其中有多个键值对。这工作'section [0] [:id]'。压扁显然不会影响它。 – Archonic
你可以发布你的'fech_all_sections'方法的代码吗?@Archonic? – MrYoshiji
也许由于该方法调用自己,数组初始化器被推到..自己?盗梦空间!但是,如果all_sections.nil没有改变,all_sections = []。 – Archonic