祖先宝石获取带有祖先ID的树



我使用祖先 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"
}, 

有人知道如何实现这一目标吗?

尝试重写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

相关内容

  • 没有找到相关文章

最新更新