Brad
Brad

Reputation: 8668

ancestor gem get tree with ancestor ids

Im using the ancestor gem to create a nested menu table.

when I render json: Menu.all

I get :

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

What i would like to do is return the id of the parent aswell (I appreciate it is the last figure in the ancestry field but I want it separate.

So I get:

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

Anyone know how to achieve this?

Upvotes: 0

Views: 444

Answers (1)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

Try overriding to_json (https://apidock.com/rails/ActiveRecord/Serialization/to_json) to include parent_id in your model class:

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

Upvotes: 0

Related Questions