본문으로 건너뛰기

기술 글

ancestry gem으로 Tree 구조 사용하기

Strol에서 Nested 메뉴를 작업하는데 해당 gem을 알게되어 공유...

표시 날짜
읽는 시간
1 min read
Tags

Strol에서 Nested 메뉴를 작업하는데 해당 gem을 알게되어 공유합니다.

재귀를 통해 직접 구현하다가 Tree를 탐색하는데 필요한 여러 기능들이 이미 해당 젬에 구현되어 있어 사용했습니다.

ancestry

gem 'ancestry'
bundle install
rails g migration add_ancestry_to_[table] ancestry:string:index
rails db:migrate
class Category < ActiveRecord::Base
   has_ancestry
end

이러면 기본적인 셋팅은 끝나게 됩니다.

아래 몇가지 사용 예시입니다.

category = Category.find_by title: "main"
category.children.create title: "sub"
## main 카테고리 아래 sub 카테고리가 생기고 sub 카테고리의 parent_id 컬럼에 main 카테고리의 id가 저장됩니다

root = Category.create title: "root"
category = Category.create title: "sub", parent: root
## 직접 parent에 지정해줘도 동작합니다

위 처럼 관계를 설정 할 수 있습니다.

그 밖에 아래 예시처럼 원하는 노드에서 부모, 자식, 형제 모두 찾기가 가능합니다

node.parent_id # 부모 노드 id
node.ancestor_ids # 모든 조상 노드 id
node.child_ids # 모든 자식 노드 id (depth: 1)
node.descendant_ids # 하위 모든 자손 노드 ids
node.sibling_ids # 모든 형제 id
node.path_ids # root까지의 모든 id