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