我有这种格式的哈希。
@company_details = {org_id1 => [employee1,employee2,employee3,employee4],org_id2 => [employee1,employee2,employee3,employee4] ...}
我想要类似的东西:
[
{
"org_id": "1234",
"employees": [
{
"employee_id": 1,
"company": "Pepsi",
},
{
"employee_id": 2,
"company": "Coke",
},
{
"employee_id": 3,
"company": "Dr. Pepper",
}
]
},
{
"org_id": "3433",
"employees": [
{
"employee_id": 5,
"company": "Mirinda",
},
{
"employee_id": 8,
"company": "7up",
},
{
"employee_id": 13,
"company": "Hersheys",
}
]
}
]
我试过像
这样的东西//index.json.jbuilder
@company_details.each do |key,value|
json.org_id key
json.employees value
end
如何自定义值以便只显示某些属性?
答案 0 :(得分:0)
试试这个:
rake db:migrate
我不太了解您的companies = @company_details.reduce([]) do |acc, (key, value)|
employees = value.map do |employee|
{
employee_id: employee.id,
company_name: employee.company.name
}
end
acc.push({ org_id: key, employees: employees })
end
json.array!(companies)
记录的内容,我猜测变量名称,但您可以根据自己的需要进行调整。
简而言之,这会将键值对中的哈希值减少为哈希数组,同时仅使用您需要的属性映射每个员工记录数组。