1
我有一個主題有很多來源(來源屬於主題)。每個來源都有一個published_date
字段。我想要的是查詢topic.sources
並將它們分組爲基於published_date的對象數組。查詢對象到數組中的組
執行此操作的一種方法是調用topic.sources
,然後按published_date
對它們進行排序。最後爲每個日期創建新的數組,並相應地將其推入到數組中。
topic.sources對象(數組):
[#<Source id: 12, topic_id: 2, published_date: "2014-11-13">,
#<Source id: 9, topic_id: 2, published_date: "2014-10-21">
#<Source id: 8, topic_id: 2, published_date: "2014-10-21">]
這應該是這樣的數組的數組:
[[#<Source id: 9, topic_id: 2, published_date: "2014-10-21">
#<Source id: 8, topic_id: 2, published_date: "2014-10-21">],
[#<Source id: 12, topic_id: 2, published_date: "2014-11-13">]]
幹得好,先生。那正是我所期待的。你能解釋'&'做什麼嗎?我以前試過'topic.sources.group_by(:published_date)',但這不起作用。 – jmoon90 2014-11-20 16:55:58
'&:something'是'{| x | x.something}'。另見http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby – 2014-11-20 16:58:18