我的应用程序中有一个表,该表具有以下字段:房间,start_at,标题和面板。
例如,我想查询按房间划分的信息,这样我就可以拥有一个json:
{
"rooms": {
"Asia": [{
"title": "Asia 1",
"panel": "Asia 1"
}, {
"title": "Asia 2",
"panel": "Asia 2"
}],
"Europe": [{
"title": "Europe 1",
"panel": "Europe 1"
}, {
"title": "Europe 2",
"panel": "Europe 2"
}]
}
}
我该如何实现?
答案 0 :(得分:2)
由于您使用的是Rails
,因此可以执行以下操作:
grouped_rooms = Room.all.group_by(&:room)
grouped_rooms_json = grouped_rooms.transform_values do |room|
room.as_json(only: [:id, :created_at])
end
{ "rooms" => grouped_rooms_json }