LoginSignup
11
17

More than 3 years have passed since last update.

[ancestry]編集画面でカテゴリー表示、選択

Posted at

フリマアプリの作成で編集画面に遷移した時、出品時に設定したカテゴリーを親(parent)、子(child)、孫(grandchild)まで表示させたい

※出品機能が完了した程で進めます

完成イメージ

Image from Gyazo

コントローラー

items_controller.rb
  before_action :set_item

~~省略~~

  def edit

    grandchild_category = @item.category
    child_category = grandchild_category.parent


    @category_parent_array = []
    Category.where(ancestry: nil).each do |parent|
      @category_parent_array << parent.name
    end

    @category_children_array = []
    Category.where(ancestry: child_category.ancestry).each do |children|
      @category_children_array << children
    end

    @category_grandchildren_array = []
    Category.where(ancestry: grandchild_category.ancestry).each do |grandchildren|
      @category_grandchildren_array << grandchildren
    end

  end

~~省略~~

  def set_item
    @item = Item.find(params[:id])
  end

edit内
上2行は孫と子のレコードを取得してます。

下3セットは親、子、孫と配列を作り、親はnameを、子と孫はancestryを格納してます。

ビュー

edit.html.haml
  .main-items
    = form_with model: @item, local: true do |f|
~~ 省略 ~~
      .wrapper.category-wrapper
        = f.label :category_id , class: 'wrapper__label category-wrapper-label', id: "wrapper__label--category" do
          カテゴリー:
          %span.required ※必須
          .category-wrapper-box
            .category-wrapper-select
              .category-wrapper-select__box
                = f.select :parent_name, @category_parent_array, {selected:@item.category.parent.parent.name}, { class: 'category-wrapper__category form-control', id: 'parent_category'}
            .category-wrapper-select#children_wrapper
              .category-wrapper-select__box
                = f.select :child_id, options_for_select(@category_children_array.map{|b| [b.name, b.id, {data:{category: b.id}}]}, {prompt: "指定なし", selected: @item.category.parent.id}),{}, {class: 'category-wrapper__category form-control', id: 'child_category'}
            .category-wrapper-select#grandchildren_wrapper
              .category-wrapper-select__box
                = f.select :category_id, options_for_select(@category_grandchildren_array.map{|b| [b.name, b.id, {data:{category: b.id}}]}, {prompt: "指定なし", selected: @item.category.id}),{}, {class: 'category-wrapper__category form-control', id: 'grandchild_category'}

各要素コントローラーで配列格納したインスタンス変数を使用

selectタグのselected:で遷移直後の表示を指定

子と孫はoptions_for_selectを使用してます。
これにより親要素を変更した際、指定なしとなり、カテゴリーを選択できるようにしてます。

孫のidをitemテーブルに紐つけてカテゴリーを判断しているので、他でわかりやすくなるよう:caregory_idと指定してます。

11
17
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
11
17