ruby-on-rails - rails jbuilder : how to build a JSON from an array with the key equals to the array values

标签 ruby-on-rails arrays ruby json jbuilder


我是一个非常新的 Rails 开发人员,我正在使用 Jbuilder按照以下方式构建我的 View :

[:aaa, :bbb, :ccc].each do |value|
  json.value do |json| #<------ Here is my error!
    json.partial! foo.send(value)
  end
end

一切正常,但 json.value,我的回复如下(显然):

[{
"value" => {...}
"value" => {...}
"value" => {...}
}]

我想要这个:

[{
"aaa" => {...}
"bbb" => {...}
"ccc" => {...}
}]

有什么想法吗?

最佳答案

来自指南:

To define attribute and structure names dynamically, use the set! method:

json.set! :author do
  json.set! :name, 'David'
end

# => "author": { "name": "David" }

解决方法是这样的:

[:aaa, :bbb, :ccc].each do |value|
  json.set! value do |json|
    json.partial! foo.send(value)
  end
end

关于ruby-on-rails - rails jbuilder : how to build a JSON from an array with the key equals to the array values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30939844/

相关文章:

javascript - d3 v4 : Using stack with histogram data?

java - 将 int 数组转换为 char 数组

ios - 如何在标签上显示数组

ruby - rbenv 和 bundler : "bad interpreter: No such file or directory"

ruby-on-rails - Rails - 在进程 8773 中通过 Spring 预加载器运行 - 在我的控制台中

javascript - 输入后需要获取coffeescript的数据

ruby - rspec 测试方法是否被调用

ruby-on-rails - 如何从 shell 脚本运行 rails command 命令?

ruby-on-rails - Rails 中的连接在哪里构建?

ruby-on-rails - 不使用 CLI 将 schema.rb 部署到 Heroku