2012-05-08 41 views
0

唯一對象我有模型「顯示」,它的has_many「表演」和性能都有一定的「位置」。 兩個或更多演出可能具有相同的位置。我如何可以收集模型

我正在尋找一種方式來獲得由節目的表演中使用的所有位置,但只有一次,(如果有三個表演與位置X,我需要得到X僅一次)。

編輯:我現在是在這種形式:對象[[performance_id:1, location_id:1],[performance_id:2, location_id:1],[performance_id:3, location_id:2]]的數組。我怎樣才能得到一個包含[1,2](唯一location_id)的數組?

回答

2

我加逗號數組:

[ 
    [performance_id:1, location_id:1], 
    [performance_id:2, location_id:1], 
    [performance_id:3, location_id:2] ].flatten.map {|h| h[:location_id]}.uniq 

=> [1, 2] 
+4

在Ruby 1.9'uniq'可以採取一個塊,所以這可能僅僅是'...壓扁.uniq {| h | h [:location_id]}',不帶'map'。 –

1

不知道這是否會爲你做它

show.performances.collect(&:location).uniq 
+0

我現在是在這種形式:對象數組[[performance_id:1,LOCATION_ID:1] [performance_id:2,LOCATION_ID:1] [performance_id:3,LOCATION_ID:2]]。我怎樣才能得到一個包含[1,2](唯一location_id)的數組? – gabitzish

1

大概就像

Location.joins(:performances).where(:performances => { :show_id => 5 }).group("locations.id") 
+0

我現在在這種形式:對象數組[[performance_id:1,LOCATION_ID:1] [performance_id:2,LOCATION_ID:1] [performance_id:3,LOCATION_ID:2]]。我怎樣才能得到包含數組[1,2](唯一的LOCATION_ID) – gabitzish

+0

your_array.collect(:LOCATION_ID).uniq – bcd