Rails树结构API

时间:2019-03-21 05:49:27

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5.1

我有JSON: JSON Link

现在,我需要创建父子关系。 这样我就可以使用数据了:

HTTP GET /:tree_id
=> Return the saved structure
HTTP GET /:tree_id/parent/:id
=> Return the list of parents
HTTP GET /:tree_id/child/:id
=> Return the list of childs

例如,我有一对宝石。 acts_as_tree&ancestry ,但是上述所有宝石都提供给我使用parent.children来获取数据。

但是我需要使用上述API。能帮我如何根据上述REST请求使用关联和模型结构来保存和获取数据。

1 个答案:

答案 0 :(得分:2)

如何创建一个像这样的模块?

module Ancestry

  def self.extended(receiver)
    receiver.class_eval do 

      define_method(:children_ids) do |children_ary=[]|
        receiver[:child].each_with_object(children_ary) do |child, children_ary|
          children_ary << child[:id]
          child.extend(Ancestry).children_ids(children_ary)
        end if receiver[:child].any?
      end

      define_method(:parent_ids) do |parents_ary=[]|
        if receiver[:child].any?
          parents_ary << receiver[:id]
          receiver[:child].each_with_object(parents_ary) do |child, parents_ary|
            child.extend(Ancestry).parent_ids(parents_ary)
          end
        end
      end

      define_method(:node) do |node_id|
        return receiver if receiver[:id] == node_id
        receiver[:child].each do |child|
          child.extend(Ancestry).node(node_id).tap do |x| 
            return x unless x.blank?
          end
        end if receiver[:child]
        {}.extend(Ancestry)
      end

      define_method(:child) do 
        receiver[:child] || []
      end

    end
  end

end

然后像这样扩展您的hash

data = {
  "id": 1,
  "child": [
    {
      "id": 1847,
      "child": [
        {
          "id": 8078,
          "child": []
        },
        {
          "id": 3380,
          "child": [
            {
              "id": 561,
              "child": []
            },
            {
              "id": 706,
              "child": []
            }
          ]
        }
      ]
    }
  ]
}.with_indifferent_access.extend(Ancestry)

现在您可以这样做:

data.children_ids
 => [1847, 8078, 3380, 561, 706]
data.parent_ids
 => [1, 1847, 3380]
data.node(1847).node(3380).child
 => [{"id"=>561, "child"=>[]}, {"id"=>706, "child"=>[]}]
data.node(9999).node(3380).child
 => []
data.node(1847).node(9999).child
 => []
data.node(1847).node(3380).node(561).child
 => []