当我调用index.html.erb中的vendor.count_owner时,我得到Stack Level Too Deep Error

供应商迁移文件如下所示

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
  1. 这个方法一遍又一遍地递归调用自己,这导致了Stack Level Too Deep Error,因为它永远不会结束.
  2. 此方法将覆盖您在其上方几行定义的belongs_to :account_owner ...关联.

试着给它起个不同的名字,比如:

def account_owner_first_name
  account_owner.first_name
end

Ruby-on-rails相关问答推荐

如何测试自定义路由?

是否从已转换为字符串的数组中提取符号?

关系 fields_for 上不允许的参数

Ruby 3 动态关键字参数

Rails:序列化数据库中的对象?

如何在 Rails 中注释掉 ERB?

$redis 全局变量与 ruby​​ on rails

上传图片 Ruby on Rails

Rails ActiveRecord:验证单个属性

rspec 共享示例与共享上下文

在 Rails 4 中检测用户代理 - 读取 HTTP 标头

Phusion 乘客(适合傻瓜!)

单击表格行(使用 bootstrap 程序)时,如何使用模式显示数据?

Rails data-disable-with re-enable 按钮

Rails - 具有空数组的强参数

rails 单数资源还是复数?

我是否必须手动卸载所有依赖的 gem?

使用 ActiveRecord 获取列名

从模型中获取验证

无论何时 gem 在 Heroku 上运行 cron 作业(job)