2014-02-11 84 views
1

我試圖從由企業員工組成的展示位置模型中創建圖表。如何訂購group_by數據

我使用下面的代碼:

def self.chart_data(business) 
business.placements.order(:month).group_by(&:month).map do |month, data| 
    hash = {month: month.strftime("%Y-%m")} 
    data.each {|placement| hash[placement.employee.name] = placement.position} 
    JSON.parse(hash.to_json) 
end 
end 

出示以下資料:

[{"month"=>"01/2014", "John"=>3, "Glen"=>4, "Frank"=>5}, {"month"=>"02/2014", "John"=>1, "Glen"=>2, "Frank"=>3}] 

我現在需要指定圖形標籤,這將是僱員的姓名。

我該如何做到這一點,同時保持員工姓名的相同順序?即

["John", "Glen", "Frank"] 

如果我得到每個企業員工的姓名,則名稱是出相對順序來佈置數據:

@business.employees.pluck(:name) 

["Frank", "John", "Glen"] 

回答

0

你可以嘗試以下方法:

chart_data = Placement.chart_data(@business) 
employees_names = chart_data.flat_map(&:keys).uniq.select{ |name| name.to_s != 'month' } 
# should return 
# => ["John", "Glen", "Frank"]