Techioz Blog

Ruby On Rails で「スタック レベルが深すぎるエラー」が発生する

概要

Index.html.erb で Vendor.account_owner を呼び出すと、スタック レベルが深すぎるエラーが発生します

ベンダー移行ファイルは次のようになります

class CreateVendors < ActiveRecord::Migration[7.0]
  def change
    create_table :vendors, id: :uuid do |t|
      t.string :name
      t.text :description
      t.string :website
      t.references :account_owner, foreign_key: { to_table: :users }, type: :uuid
      t.jsonb :data_classification, default: '{}', null: false
      t.integer :auth_type, default: 0
      t.integer :risk, default: 1
      t.datetime :engagement_date
      t.datetime :last_review_date
      t.boolean :is_active, default: true
    
      t.timestamps
    end
  end
end

ベンダーモデルは次のようになります

class Vendor < ApplicationRecord
  store_accessor :data_classification, :employee_data, :corporate_data, :customer_data, :personal_data, :healthcare_data, :payments_data
 
  enum :auth_type, { Unknown: 0, SSO: 1, Password: 2 }
  enum :risk, { Low: 0, Medium: 1, High: 2 }

  belongs_to :account_owner, class_name: 'User', foreign_key: :author_id
  has_many :documents, as: :documentable


  def account_owner 
    account_owner.first_name
  end
end

ユーザーモデルは次のようになります

class User < ApplicationRecord

  ...
  has_many :authored_policies, class_name: 'Policy', foreign_key: 'author_id'
  has_many :created_groups, class_name: 'Group', foreign_key: 'creator_id'
  has_many :vendors, foreign_key: 'account_owner_id'
    

  
  def full_name
    first_name + " " + last_name
  end
end

プラットフォーム上で同様のエラーメッセージを確認しましたが、この特定の状況には対処していませんでした。 おそらく何かが足りないと思うので助けが必要です

解決策

Vendor クラスには次のようなものがあります。

def account_owner 
  account_owner.first_name
end

次のような別の名前を付けてみてください。

def account_owner_first_name
  account_owner.first_name
end