Rails,创建树状结构.JSON输出

Jin*_*dam 3 ruby json ruby-on-rails ruby-on-rails-3

我有一个数据表,可以互为父母或孩子,用字段parent_id处理(我使用的是act_as_tree gem)

第一级项目的父项为0

可能会有无数的孩子.我想输出为JSON.最后的输出就是这样的

{
   "feild1": "dd",
   "filed2": "ee",
   "child" : {
       "feild1": "dd",
        "filed2": "ee",
        } 
   "child" : {
        "feild1": "dd",
        "filed2": "ee",
                 "child" : {
                      "feild1": "dd",
                      "filed2": "ee",
                  } 
        } 

}
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的就是这个

def coa_tree
   @roots = Coa.find(:all, :conditions => ['parent_id = ?', 0])
   @response = @roots

   @roots.each do |root|
     logger.debug "roots each"
      output = root
      root.children.each do |child|
           output = {:child => output, :child => child}

      end

   end
   respond_with(@response)
end
Run Code Online (Sandbox Code Playgroud)

显然我甚至没有接近解决问题.如果有人能指出我正确的方向,我会非常感激.也许有一个我不知道的插件可以帮助我解决这个问题.谢谢.

Tod*_*ell 14

您的JSON示例无效,因为同一对象中有多个具有相同名称的键,但是从ActiveRecord对象输出树结构作为JSON绝对是可能的.

尝试将这样的方法添加到模型类中:

class Coa < ActiveRecord::Base
  def to_node
    { "attributes" => self.attributes,
      "children"   => self.children.map { |c| c.to_node }
    }
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下命令将整个树检索为JSON:

root = Coa.find(:first, :conditions => ["parent_id = ?", 0])
root.to_node.to_json
Run Code Online (Sandbox Code Playgroud)