如何将活动记录层次结构解析为javascript数组

时间:2017-09-23 17:11:30

标签: javascript jquery ruby-on-rails activerecord treeview

我正在尝试在我的rails应用中的机构模型中实现树视图,我已将ancestry gem添加到我的模型中,并且treeview添加到我的模型中视图哪个也有效

但我真的不知道发送正确数据的方法,我的观点需要一个像这样的js数组:

var tree = [
  {
    text: "Parent 1",
    nodes: [
      {
        text: "Child 1",
        nodes: [
          {
            text: "Grandchild 1"
          },
          {
            text: "Grandchild 2"
          }
        ]
      },
      {
        text: "Child 2"
      }
    ]
  },
  {
    text: "Parent 2"
  },
  {
    text: "Parent 3"
  },
  {
    text: "Parent 4"
  },
  {
    text: "Parent 5"
  }
];

我已经创建了一个Web服务来返回一个文本,然后在加载时调用它:

request = $.ajax({
        url: '/get_institutions_tree',
        type: 'GET',
        dataType: "text",
        success: function(data){
            $('#tree').treeview({data: data});
        }
    });

但我真的不知道如何构造数组,我正在尝试手动解析它,我在我的控制器中有这个(我会尝试以某种方式稍后递归):

def get_institutions_tree
    institutions = Institution.roots

    data = "var data = [ "
    institutions.each do |institution|
      data << get_subtree(institution)
    end
    data << " ];"

    render json: data
  end

  private

  def get_subtree(institution)
    subdata =  "{"
    subdata << "text: '" << institution.name << "',"
    subdata << "}"
  end

现在Web服务正在返回此(1深度),但它返回一个文本(“string”),如果我只是分配它就不起作用:

var data = [ {text: 'Nacional Bogota',}{text: 'Nacional Cali',} ];

我该如何使这项工作?是否有更好/更清洁的方法来实现这一目标? 提前谢谢

1 个答案:

答案 0 :(得分:0)

我还没有使用祖先或树视图宝石,但似乎你正在构建一个json对象数组作为字符串,而你可以使用数组和json对象。

在机构循环中,我会填充一系列根。类似的东西:

data = []
institutions.each do |institution|
  data << get_subtree(institution)
end

然后,get_subtree应该是递归的,以获得所有级别。它应该建立一个json。类似的东西:

def get_subtree(institution)
  sub = { :text => institution.name }
  children = institution.children
  if children
    sub.nodes = []
    children.each do |child|
      sub.nodes << get_subtree(child)
    end
  end
  sub
end