简体   繁体   中英

How to get all the descendants of an object in Ruby on Rails

I'm have models related as follows:

GrandParent 
  has_many :kids
  has_many :grand_children, through: :kids
Kid 
  belongs_to :grand_parent
  has_many :grand_kids
GrandKid
  belongs_to :kid

I would just like to call .descendants on an object, and get all the objects that belong to its 'lineage'.

I thought that using the ancestry gem would give me the .descendants method I wanted, but it only creates an additional index on a single class, allowing you to get descendants within said class.(great for things like comments & replies, but not useful for my problem) My code is not really necessary to understand the problem, but here it is for those interested: https://gist.github.com/bjlinville1/8425bfe88bc7060209e8

I believe you're interpreting the ancestry gem incorrectly. It looks like you expect Region to show up as a child of Country. Is that right?

Ancestry is useful for tree like structures (think folders -> sub folders -> child sub folders -> etc.)

Applying has_ancestry within your Country model would allow you to create countries within countries. But I don't believe that's what you're looking for.

Regardless, you can set up those relations by setting the "parent_id" attribute for a country when creating/updating it within the controller. Just set it to the ID of the parent country. Same for regions if you want a tree structure of regions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM