在 rails 中呈现自定义 json 数组

render custom json array in rails

现在我在@hours 中有一组小时数与用户和 hour_type 的关系。

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

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

@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