【发布时间】:2019-08-21 11:18:52
【问题描述】:
这里我现在有@hours 中的小时数组,其中包含用户和小时类型的关系。
Hours_controller.rb
def index
@houra = Hour.all
@users = User.where(id: @hours.map(&:user_id).uniq)
@hour_type = HourType.where(id: @hours.map(&:hour_type_id).uniq)
render json: {
users: [@users],
hour_type: [@hour_type],
hours: @hours
}
end
上面的代码给我下面的响应。
{
"users": [
"id": 6
],
"hour_type": [
"id": 69
],
"hours": [
{
"id": 1,
},
{
"id": 12
},
{
"id": 2,
}
]
}
但现在我想要一个像下面这样的 json 响应。
{
"users":[
0:{
user_id:2
},
1:{
user_id:3
},
],
"hours":[
0:[
{
hour_type_id:"1"
hours: [
{
hour_id: 1
},
hour_id: 2
},
]
},
1:[
{
hour_type_id:"1"
hours: [
{
hour_id: 1
},
{
hour_id: 2
},
]
}
}
如何在 json 中获得相同的响应?
在这里,我添加了一些接近结果的内容
@hours = Hour.all
@users = User.where(id: @hours.map(&:user_id).uniq)
@hour_types = HourType.where(id: @hours.map(&:hour_type_id).uniq)
result = {
users: @users,
hours: []
}
@hour_types.each do |hour_type|
hour_type_hash = {
hour_type: hour_type,
hours: Hour.where(hour_type_id: hour_type.id).all
}
result[:hours] << hour_type_hash
end
渲染 json:结果
现在只想在用户之前添加 id
【问题讨论】:
-
“我该怎么做才能在 json 中获得相同的响应”——您可以编写生成 json 的代码。
-
我已经尝试了大部分情况,但我无法获得像 @AlekseiMatiushkin 这样的相同输出
-
你能展示一下
@hours的样子吗?是一样的结构吗?问题是如何从哈希到 json,或者如何将数据正确映射到 json 中所需的格式/顺序/嵌套?在这种情况下,我们肯定需要查看数据如何帮助您进行转换。 -
请再读一遍@nathanvda
-
更多的模式推荐,但对于复杂和非标准的有效负载,您应该考虑使用像github.com/Netflix/fast_jsonapi 这样的序列化程序。它将为您提供一个很好的舞台来格式化您的 json,与您的控制器逻辑的其余部分分开。
标签: ruby-on-rails json ruby api response