Skip to content
Advertisement

Association for the child of the child in ruby on rails

Example of data in User table enter image description here

Expected result in rails console, grandfather.grandchildren and grandmother.grandchildren should return the same group of objects:

This is my association now in User.rb model.

Output in rails console now:

Advertisement

Answer

You can’t get the grandchildren from a grandparent by going through its children because it implies that their father/mother ids are equal to the grandparent, it doesn’t travel through the grandchildren parents:

You can add a callable to the grandchildren relationship, similar to the one for children, but this time extracting the grandparent children ids, and using the IN clause to filter those user rows matching those ids, with their father/mother ids:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement