您如何在 JBuilder 中呈现散列值的部分?
How do you render a partial to a hash value in JBuilder?
我有一个类似于以下内容的 tree-like object 图表:
{
: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 => {}
}
}
}
我想生成反映此结构的 JSON。 child嵌套不知道有多深,每一层的属性都是一样的。 children 散列中的键很重要,必须保留。
我想用一个JBuilder partial 来表示一个level,然后递归调用它。到目前为止,这是我的模板:
# _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 输出中。如何将部分结果映射到特定的 hash/object 键?
我找到了答案。虽然它似乎在很大程度上没有记录,但 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
我有一个类似于以下内容的 tree-like object 图表:
{
: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 => {}
}
}
}
我想生成反映此结构的 JSON。 child嵌套不知道有多深,每一层的属性都是一样的。 children 散列中的键很重要,必须保留。
我想用一个JBuilder partial 来表示一个level,然后递归调用它。到目前为止,这是我的模板:
# _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 输出中。如何将部分结果映射到特定的 hash/object 键?
我找到了答案。虽然它似乎在很大程度上没有记录,但 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