我有一个类似于以下的树状对象图:
{
:name => "Grandparent",
:children => {
:child_a => {
:name => "Parent A",
:children => {
:grandchild_a_a => {
:name => "Child A-A",
:children => {}
}
:grandchild_a_b => {
:name => "Child A-B"
:children => {}
}
}
}
:child_b => {
:name => "Parent B",
:children => {}
}
}
}
我想生成反射(reflect)此结构的 JSON。不知道子嵌套到多深,每层属性都一样。子哈希中的键很重要,必须保留。
我想使用 JBuilder 部分来表示一个级别,然后递归调用它。到目前为止,这是我的模板:
# _level_partial.json.jbuilder
# passing the above object graph as :level
json.name level[:name]
json.children do
level[:children].each do |key, child|
# How do I map the following to the given key?
json.partial! "level_partial", :level => child
end
end
我可以很容易地通过部分调用为每个 child 生成 JSON,但这会将它直接插入到 JSON 输出中。如何将部分结果映射到特定的哈希/对象键?
最佳答案
我找到了答案。尽管它似乎在很大程度上没有记录,JBuilder.set!
可以接受块而不是显式值。该块可以调用部分,然后将其分配给哈希。
json.name level[:name]
json.children do
level[:children].each do |key, child|
json.set! key do
json.partial! "level_partial", :level => child
end
end
end
关于ruby-on-rails - 你如何在 JBuilder 中渲染散列值的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660367/