Rails Tree Structure API [关闭]

问题描述 投票:-1回答: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请求的数据。

ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5.1
1个回答
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
 => []
© www.soinside.com 2019 - 2024. All rights reserved.