LoginSignup
0
3

More than 3 years have passed since last update.

【Rails】ancestryを用いた多階層カテゴリー機能の実装『編集フォーム編』

Last updated at Posted at 2020-06-21

目標

ezgif.com-video-to-gif.gif

開発環境

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

前提

下記実装済み。

Slim導入
Bootstrap3導入
Font Awesome導入
ログイン機能実装
投稿機能実装
多対多のカテゴリー機能実装
多階層カテゴリー機能実装(準備編)
多階層カテゴリー機能実装(seed編)
多階層カテゴリー機能実装(作成フォーム編)

実装

1.コントローラーを編集

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

【解説】

① 中間テーブルから編集する本に対応するレコードを全て抽出し、削除する。

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

2.ビューを編集

books/edit.html.slim
/ 追記
.category-form
  = label_tag 'ジャンル'
  = select_tag 'parent_id', options_for_select(@category_parent_array), class: 'form-control', id: 'parent-category'
  i.fas.fa-chevron-down
br

注意

turbolinksを無効化しないとセレクトボックスが非同期で動作しないので、必ず無効化しておきましょう。

turbolinksを無効化する方法

続編

多階層カテゴリー機能実装(Bootstrapeでウィンドウ作ってみた編)

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3