【问题标题】:How do you render a partial to a hash value in JBuilder?如何在 JBuilder 中将部分渲染为哈希值?
【发布时间】:2015-10-18 01:38:00
【问题描述】:

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

{
  :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 输出。如何将部分结果映射到特定的哈希/对象键?

【问题讨论】:

    标签: ruby-on-rails json jbuilder


    【解决方案1】:

    我找到了答案。尽管它似乎在很大程度上没有记录,但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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2015-11-03
      • 2015-07-03
      • 2013-12-14
      相关资源
      最近更新 更多