[Java] [Rails] Implementation of multi-level category function using ancestry Edit form

less than 1 minute read

Target

ezgif.com-video-to-gif.gif

Development environment

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

Premise

Implemented below.

Slim introductionBootstrap3 installedFont Awesome introductionImplementation of login functionPosting function implementationMany-to-many category function implementationMulti-level category function implementation (preparation)Multi-level category function implementation (seed) ・[Multi-level category function implementation (creation form)] (https://qiita.com/matsubishi5/items/4afb4a4f307023126c66)

Implementation

1. Edit the controller

books_controller.rb


def edit
  unless @book.user == current_user
    redirect_to books_path
  end
  @category_parent_array = Category.category_parent_array_create
end

def update
  if @book.update(book_params)
    book_categories = BookCategory.where(book_id: @book.id)
    book_categories.destroy_all
    BookCategory.maltilevel_category_create(
      @book,
      params[:parent_id],
      params[:children_id],
      params[:grandchildren_id]
    )
    redirect_to @book
  else
    @category_parent_array = Category.category_parent_array_create
    render'edit'
  end
end

[Explanation]

① Extract and delete all records corresponding to the book to be edited from the intermediate table.

book_categories = BookCategory.where(book_id: @book.id)
book_categories.destroy_all

2. Edit the view

slim:books/edit.html.slim


/ Addendum
.category-form
  = label_tag'genre'
  = select_tag'parent_id', options_for_select(@category_parent_array), class:'form-control', id:'parent-category'
  i.fas.fa-chevron-down
br

Note

If you do not disable turbolinks, the select box will not work asynchronously, so be sure to disable it.

How to disable turbolinks

Sequel

Multi-level category function implementation (I tried making a window with Bootstrape)