我的 rails 应用程序中有以下查询,但其结果没有属性名称,因此我无法在 amcharts 中使用它
EmployeeDepartment.joins(:states).group
("employee_departments.name").count
结果是:{"Academic Support":1}
如何使它像这样{"department_name":"Academic Support","department_count":1}
我的 rails 应用程序中有以下查询,但其结果没有属性名称,因此我无法在 amcharts 中使用它
EmployeeDepartment.joins(:states).group
("employee_departments.name").count
结果是:{"Academic Support":1}
如何使它像这样{"department_name":"Academic Support","department_count":1}
假设你有一个这样的哈希:
hash = { "Academic Support" => 1, "Another Department" => 3, "Something Else" => 4 }
您可以使用map
将其转换为包含所需内容的哈希数组。
hash.map { |k, v| { "department_name" => k, "department_count" => v } }
=> [{"department_name"=>"Academic Support", "department_count"=>1},
{"department_name"=>"Another Department", "department_count"=>3},
{"department_name"=>"Something Else", "department_count"=>4}]
如果您的散列只包含一个键/值对,而您只想要另一个散列,您可以试试这个:
Hash[[["department_name", "department_count"], hash.first].transpose]
或者更简单...
{ "department_name" => hash.keys.first, "department_count" => hash.values.first }
我通过以下步骤解决了我的问题:
以下代码:
EmployeeDepartment.joins(:states).group
("employee_departments.name").count
生成这个rails console
SELECT COUNT(*) AS count_all, employee_departments.name AS employee_departments_name FROM "employee_departments" INNER JOIN "tickets" ON "tickets"."employee_department_id" = "employee_departments"."id" INNER JOIN "states" ON "states"."id" = "tickets"."state_id" GROUP BY employee_departments.name
我使用了console
以下内容中生成的内容:
@department_count = EmployeeDepartment.find(:all,
:select => 'employee_departments.name AS employee_departments_name, COUNT(*) AS department_counter',
:joins => 'INNER JOIN tickets ON tickets.employee_department_id = employee_departments.id INNER JOIN states ON states.id = tickets.state_id',
:group => 'employee_departments.name')
现在 amcharts 中的结果是:
var chartData = [{"department_counter":1,"employee_departments_name":"Academic Support"}];