【问题标题】:render custom json array in rails [closed]在rails中呈现自定义json数组[关闭]
【发布时间】: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


【解决方案1】:

这是一种非常幼稚的渲染方式,但这应该可以帮助您入门:

@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.map{|u| {user_id: u.id} },
  hours: [] 
} 

@hour_types.each do |hour_type| 
  hour_type_hash = { 
    hour_type_id: hour_type.id, 
    hours: Hour.where(hour_type_id: hour_type.id).all.map{|h| {hour_id: h.id} } 
  }
  result[:hours] << hour_type_hash  
end 

render json: result_hash 

【讨论】:

  • 我试过了,但它显示了这一行用户中的语法错误:@users.map{|u| user_id: u.id},
  • 对,这当然是未经测试的代码。多哈。我们应该更明确地说明我们正在创建/返回一个哈希。它现在应该工作吗? (我在两个地方更改/修复了它)。现在可以用了吗?
猜你喜欢
  • 1970-01-01
  • 2013-09-20
  • 2010-09-20
  • 2014-06-19
  • 2020-05-16
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
相关资源
最近更新 更多