祖先宝石得到祖先ids的树

时间:2018-05-16 12:04:42

标签: ruby-on-rails json api ancestry

我使用祖先gem创建一个嵌套的菜单表。

当我render json: Menu.all

我明白了:

[
    {
        "id": 1,
        "label": "Menu"
        "created_at": "2018-05-14T14:28:03.883Z",
        "updated_at": "2018-05-14T14:28:03.883Z",
        "ancestry": null
    },
    {
        "id": 2,
        "label": "Menu 1-1",
        "created_at": "2018-05-14T14:28:13.982Z",
        "updated_at": "2018-05-14T14:28:13.982Z",
        "ancestry": "1"
    },
    {
        "id": 3,
        "label": "Menu 1-1-1",
        "created_at": "2018-05-14T14:28:13.982Z",
        "updated_at": "2018-05-14T14:28:13.982Z",
        "ancestry": "1/2"
    },
 etc

我想做的是返回父母的身份(我很欣赏它是祖先领域的最后一个数字,但我希望它分开。

所以我得到了:

[
    {
        "id": 1,
        "label": "Menu"
        "created_at": "2018-05-14T14:28:03.883Z",
        "updated_at": "2018-05-14T14:28:03.883Z",
        "ancestry": null,
        "parent_id":null
    },
    {
        "id": 2,
        "label": "Menu 1-1",
        "created_at": "2018-05-14T14:28:13.982Z",
        "updated_at": "2018-05-14T14:28:13.982Z",
        "ancestry": "1",
        "parent_id":"1"
    },
    {
        "id": 3,
        "label": "Menu 1-1-1",
        "created_at": "2018-05-14T14:28:13.982Z",
        "updated_at": "2018-05-14T14:28:13.982Z",
        "ancestry": "1/2",
        "parent_id":"2"
    }, 

任何人都知道如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

尝试覆盖to_jsonhttps://apidock.com/rails/ActiveRecord/Serialization/to_json)以在模型类中包含parent_id

class Menu < ActiveRecord::Base
  def to_json
    super(methods: [:parent_id])
  end
end