[Ruby] [Rails] Implementation of multi-level category function using ancestry seed

less than 1 minute read

Development environment

・Ruby: 2.5.7 Rails: 5.2.4 ・Vagrant: 2.2.7 ・VirtualBox: 6.1 ・OS: macOS Catalina

Premise

Implemented below.

Posting function implementationMany-to-many category function implementationMulti-level category function implementation (preparation)

Implementation

id name ancestry
1 Business nil
2 ** Finance** 1
3 Share 1/2
4 Exchange 1/2
5 Tax 1/2
6 Economy 2
7 Japan Economy 1/6
8 International Economy 1/6
9 Management 3
10 Business Management 1/9
11 Strategy/Strategy 1/9
12 Company/Opening 1/9
13 Marketing 4
14 Business Management 1/13
15 Strategy/Strategy 1/13
16 Company/Opening 1/13

If you want to have the above-mentioned parent-child relationship in the category of the book, create the data as follows.

seed.rb


business = Category.create(name:'business')
business_children_array = ['Finance','Economy','Management','Marketing']
business_grandchildren_array = [
  ['Stock','Exchange','Tax'], # Financial child
  ['Japanese economy','International economy'], # Economic child
  ['Business Administration','Strategy/Management','Startup/Opening'], #Child of Management
  ['Advertising','Sales','Development'] # Child of Marketing
]

business_children_array.each_with_index do |children, index|
  children = business.children.create(name: children)
  business_grandchildren_array[index].each do |grandchildren|
    children.children.create(name: grandchildren)
  end
end

Sequel

Multi-level category function implementation (creation form)