2016-03-17 73 views
1

我正在嘗試爲我的商家位置創建一個目錄頁面。我可以輕鬆地列出所有位置,但更願意列出位置的狀態,然後列出位於該州的位置城市。然後在狀態下面,列出位置名稱。Ruby - 解析出位置城市列表,然後取出城市列表並解析出每個城市的位置

我目前正在獲取下面一行所有的位置。

@locations = @brand.locations.all 

然後我爲州和城市創建兩個空白數組。

@states = [] 
@cities = [] 

一旦我創建了數組,我想遍歷這些位置來將狀態和城市附加到它們的適當數組。

@locations.each do |location| 
    @states << location.state 
    @cities << location.city 
end 

我該如何將位置追加到城市陣列中相應的城市?我正在考慮在@cities數組中使用哈希,但從那裏開始就陷入了困境。對不起,如果這似乎是一個基本問題。

回答

2

看一看#group_by#map

Hash[@locations.all.group_by(&:state).map{|k,v| [k, v.group_by(&:city)]}]

這會產生這樣的:

{ 
    "NY": { 
    "Schenectady": [ ... locations in schenectady new york ... ], 
    "Manhattan": [ ... locations in manhattan new york ...] 
    }, 
    "TX": { 
    "Austin": [ ... locations in austin texas ... ] 
    } 
} 
+1

是忙着寫劣質答案 – toddmetheny