Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在JBuilder中,如何将部分呈现为哈希值?_Ruby On Rails_Json_Jbuilder - Fatal编程技术网

Ruby on rails 在JBuilder中,如何将部分呈现为哈希值?

Ruby on rails 在JBuilder中,如何将部分呈现为哈希值?,ruby-on-rails,json,jbuilder,Ruby On Rails,Json,Jbuilder,我有一个树状的对象图,类似于以下内容: { :name => "Grandparent", :children => { :child_a => { :name => "Parent A", :children => { :grandchild_a_a => { :name => "Child A-A", :children => {}

我有一个树状的对象图,类似于以下内容:

{
  :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。我不知道子嵌套有多深,每个级别的属性都是相同的。子散列中的键很重要,必须保留

我想使用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

我可以很容易地通过部分调用为每个子级生成JSON,但这会将其直接插入JSON输出。如何将分部的结果映射到特定的哈希/对象键?

我找到了答案。尽管它似乎大部分没有文档记录,
JBuilder.set可以接受块而不是显式值。该块可以调用partial,然后将其分配给散列

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