如何以列式格式返回json
假设用户表有3列(Name, age, location)
,
Jack, 18, Taiwan
Mary, 27, Japan
预期的JSON响应格式(按柱状)
{
name:["Jack", "Mary"],
age: [18, 27],
location: ["Taiwan", "Japan"]
}
如何在Rails上完成它?
答案 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