【问题标题】:ancestor gem get tree with ancestor ids祖先宝石获取具有祖先ID的树
【发布时间】:2018-05-16 12:04:42
【问题描述】:

我正在使用祖先 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(我很欣赏它是祖先字段中的最后一个数字,但我希望它分开。

所以我得到:

[
    {
        "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"
    }, 

有人知道如何实现吗?

【问题讨论】:

    标签: ruby-on-rails json api ancestry


    【解决方案1】:

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

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

    【讨论】:

    • 但是父id不是列,我需要从祖先列中提取或者使用gem提供的方法
    • 您的意思是,当您在 Menu 的实例上调用 parent_id 时,您会收到“未定义方法”错误?
    • 根据github.com/stefankroes/ancestry#navigating-your-tree,我相信你应该定义方法。
    • 好的,我将您的代码添加到我的模型中,但仍然得到相同的结果,我需要在控制器索引调用中更改一些内容吗?
    • 感谢您的帮助,我设法使用 jbuilder 解决了这个问题并用它构建了对象。还是谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    相关资源
    最近更新 更多