简体   繁体   中英

Rails 3 ActiveRecord Selecting Parent Child recursion from Single Table

I have a table called categories where the table structure and data is

id | parent_id | name
------------------------
1  | 0         | Computers    // parent
2  | 0         | TV           // parent
4  | 1         | Motherboards // child - to - id(1)
5  | 4         | Mercury
6  | 5         | Mecrury XXX
7  | 6         | Mecrury YYY

(Where parent_id is id of another row)

Show how can i get parent/child results using Rails3 Activerecord query interface . (Or any other solution).

If i search for Computer how can i get all the childs -> super child under that parent category.

Example Result will - Computers -> Motherboards -> Mercury XXX -> Mercury YYY

Thank You

You should take a look at the awesome nested set gem.

It allows you to call something like this to get all descendant nodes:

Node.root.self_and_descendants

The ancestry seems good as well, though I haven't used it myself.

Both gems will require a migration of your data but it's for the better, as using just a parent_id for navigating child nodes isn't the most efficient.

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