[Ruby] [Rails] What I learned from a little stumbling block when using ancestry

1 minute read

Introduction

As a memorandum, I wanted to implement a “column with a hierarchy” when I made a fashion e-commerce site by personal production, and I learned from a little stumbling block when using ** ancestry ** that realizes exactly that. I will leave it.

** Also, this article is not a procedure manual, but an introduction to the mistakes that beginners tend to make! ** **

What you want to achieve

I want to enable the following dynamic select box using ancestry ** even when editing **.

Image from Gyazo

Premise

It is assumed that the controller defines the action to search the child hierarchy as shown below.
Ajax also defines search_child firmly.

(controllers/items_controller.rb)

(abridgement)

  def edit
    child_category = @item.category

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

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

  def search_child
    respond_to do |format|
      format.html
      format.json do
        @children = Category.find(params[:parent_id]).children
      end
    end
  end

(abridgement)

end

(abridgement)

  $("#parent-form").on("change", function() {
    var parentValue = document.getElementById("parent-form").value;
    if (parentValue != "---") {
      $('#category__box--children').remove();
      $.ajax({
        url     : 'search_child',
        type    : 'GET',
        data    : { parent_id: parentValue },
        dataType: 'json'
      })

(abridgement)

Doesn’t search when editing! ??

Image from Gyazo

I implemented it and newly registered it, and I thought that there would be no problem, so I froze it.

Solution

It’s very simple, I just added the routing.

(config/routes.rb)
Rails.application.routes.draw do

(abridgement)

  resources :shops, only: [:new, :create, :show, :edit, :update, :destroy] do
    resources :items, only: [:new, :create, :edit, :update, :destroy] do
      collection do
        get "search_child", defaults: { format: "json" }
      end
     #####↓ Add here ↓ #####
      member do
        get "search_child", defaults: { format: "json" }
      end
    #####↑ Add here ↑ #####
    end
(abridgement)

Lesson

When the implementation range of one function expands, I tend to scoop up my feet, and I just focused on the content of the code I wrote for this error, and I spent some time. ..

I regret that it is important to understand the flow of the code until it works again and to look at the doubts!