ruby-on-rails - 如何使用 jbuilder 创建此自定义 JSON 布局
问题描述
我正在尝试使用 jbuilder 创建这个 JSON 布局:
"entities" : {
"users": {
1: {name: 'abs', age: 44},
2: {name: 'arms', age: 12},
3: {name: 'legs', age: 34},
}
}
到目前为止我有这个:
json.entities do
json.users @response.users do |user|
json.(user, :id)
end
end
但这又回来了:
entities: {
users: [
{
id: 1
}
]
}
我需要将“users”中的键设为 user.id 值,然后列出属性。
解决方案
这将为您提供所需的哈希值。.to_json
如果需要字符串,则必须调用它。
hash = {users:{}}
@response.users.pluck(:id, :name, :age).each {|u| hash[:users][u[0]] = {name: u[1], age: u[2]}]}
# hash.to_json
推荐阅读
- exception - IMap InternalKey 的 HazelcastSerializationException - 如何调试或记录
- javascript - Node.js express - 无需进入路由函数即可获取路由参数以进行快速分析跟踪
- php - SafeMySQL 将 FLOAT 替换为 INT
- spring-boot - 执行 SQL Builder 类时出现 SQL UNINITIALIZED 错误 - MyBatis Springboot
- bash - 将值从 csv 文件存储到数组 Ubuntu
- jsp - 用于构建对象列表的 JSP EL 表达式
- postgresql - @Tailable(spring-data-reactive-mongodb) 等效于 spring-data-r2dbc
- python - 如何到达并添加新行到在 Django 框架中制作的 Web 服务器数据库?
- excel - excel中是否有sum oa完成的功能?
- javascript - 获取不是基于 jquery 的库 Rails 6 Webpack 的函数错误