使用jBuilder构建复杂数组

问题描述 投票:0回答:1

我在Rails应用程序中使用jBuilder和jsTree(https://www.jstree.com/docs/json/),并尝试构建如下数组:

[
{
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
},
{...},
{...}
]

我之前用一个简单的json.array!和一个do循环来执行此操作,并从数据库中获取了一组结果。那里没有问题。问题是我有多态父母,即有不同的模型。我将其等同为一个示例,其中有一个“产品”和“设备”,并且它们都嵌套在下面。我要列出所有项目(带有子注释),然后列出所有设备,然后为其列出子注释。我本质上需要这样的循环:

[

projects do |p|
  json.id id
  json.parent "#"
  ...
end

equipment do |e|
  json.id id
  json.parent "#"
  ...
end

comments do |c|
  json.id id
  json.parent c.parent_id
  ...
end

]

这样,我可以建立数据散列以供jsTree解析。 jBuilder的文档不是很好,并且不确定如何或可以做到这一点。

ruby-on-rails jstree jbuilder
1个回答
0
投票

我只是跳过jBuilder。它的速度很慢,您真的需要一个超级笨拙的DSL来构建JSON对象吗?毕竟所有的Ruby哈希和数组都可以清晰地映射到JSON类型。

class JsTreeSerializer
  # @param [Array] records
  # @param [Mixed] context - used to call view helpers
  def initialize(records, context: nil)
    @records = records
    @context = context
  end

  def serialize
    json = @records.map do |record|
      { 
         id: record.id,
         parent: record.parent_id,
         icon: context.image_url('icon.gif')
         # ...
      }
    end
  end
end

用法:

class MyController 
  def index
     @records = get_all_the_types
     respond_to do |f|
       format.json do
         render json: JsTreeSerializer.new(
           @records, 
           context: view_context
         ).serialize
       end
     end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.