以列方式返回json

时间:2015-01-21 15:52:01

标签: ruby ruby-on-rails-3 ruby-on-rails-4

如何以列式格式返回json

假设用户表有3列(Name, age, location)

用户表

Jack, 18, Taiwan
Mary, 27, Japan

预期的JSON响应格式(按柱状)

{
 name:["Jack", "Mary"],
 age: [18, 27],
 location: ["Taiwan", "Japan"]
}

如何在Rails上完成它?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

data = {
  name: User.pluck(:name),
  age: User.pluck(:age),
  location: User.pluck(:location)
}

render json: data

但请注意,这将查询数据库3次!

编辑:如果您想在1个查询中执行所有操作,请执行以下操作:

data = {
  name: [],
  age: [],
  location: []
}

User.pluck(:name, :age, :location).each do |u|
  data[:name] << u[0]
  data[:age] << u[1]
  data[:location] << u[2]
end

render json: data