Ruby on rails 将ActiveRecord映射为Rails上的动态键值对
我想将ActiveRecord查询映射为键值对 我想得到表单中的Ruby on rails 将ActiveRecord映射为Rails上的动态键值对,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我想将ActiveRecord查询映射为键值对 我想得到表单中的json\u结果s { "16": "2017-10-16T17:04:51.000Z" } { "id": 16, "date": "2017-10-16T17:04:51.000Z" } 但是下面的代码以表单的形式获取结果 { "16": "2017-10-16T17:04:51.000Z" } { "id": 16, "date": "2017-10-16T17:04:51.000Z" } r.id:r.started
json\u结果
s
{ "16": "2017-10-16T17:04:51.000Z" }
{ "id": 16, "date": "2017-10-16T17:04:51.000Z" }
但是下面的代码以表单的形式获取结果
{ "16": "2017-10-16T17:04:51.000Z" }
{ "id": 16, "date": "2017-10-16T17:04:51.000Z" }
r.id:r.started\u在
不起作用
@results = Visit.all
json_results = {
data: @results.map do |r| {
id: r.id,
date: r.started_at
} end
}
如何在Rails中实现这一点,因为我在这方面遇到了一些麻烦 试试这个:
json_results = {
data: @results.map do |r|
{ r.id => r.started_at }
end
}
例如:
puts ({4 => "foo"}.to_json)
# {"4":"foo"}
试试这个:
json_results = {
data: @results.map do |r|
{ r.id => r.started_at }
end
}
例如:
puts ({4 => "foo"}.to_json)
# {"4":"foo"}
另一种方法是将
pull
与一起使用以
json_results = Visit.pluck(:id, :started_at).to_h
另一种方法是将pull
与一起使用以
json_results = Visit.pluck(:id, :started_at).to_h
你的意思是,你想构建没有键的JSON?我不确定它是否是有效的JSON。你的JSON是无效的,因为其他人已经指出,{“16”,“2017-10-16T17:04:51.000Z”
不是有效的JSON。也许你想要的是一个数组[“16”,“2017-10-16T17:04:51.000Z”
?我认为这是打字错误,期望的结果是{“16:“2017-10-16T17:04:51.000Z”}
抱歉,伙计们,这是一个输入错误。你的意思是,你想构建没有键的JSON?我不确定,这是一个有效的JSON。你的JSON无效,正如其他人指出的那样,
{“16”,“2017-10-16T17:04:51.000Z}
不是有效的JSON。也许你想要的是一个数组[“16”,“2017-10-16T17:04:51.000Z”
?我认为这是一个输入错误,期望的结果是{“16:“2017-10-16T17:04:51.000Z”}
对不起,伙计们,这是一个输入错误。