Ruby on Rails 5随机NameError:控制台中命名空间模型上的未初始化常量

时间:2018-05-10 16:30:42

标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord

我在 app / models / admin 文件夹中有两个命名空间模型:

transactiontype.rb:

module Admin
  class TransactionType < ApplicationRecord
    self.table_name = "transactiontypes"

    has_many :transactions
  end
end

transaction.rb:

module Admin
  class Transaction < ApplicationRecord
    self.table_name = "transactions"

    belongs_to :transactiontype
  end
end

schema.rb 中,表定义如下所示:

  create_table "transactiontypes", force: :cascade do |t|
    t.string "description", limit: 30, null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

create_table "transactions", force: :cascade do |t|
    t.string "description", limit: 30, null: false
    t.bigint "transactiontype_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

add_foreign_key "transactions", "transactiontypes"

现在,如果我打开rails控制台并输入:

管理:: TransactionType.all

我收到此错误:

NameError:未初始化的常量Admin :: TransactionType

奇怪的是,过去一小时我一直在打开和关闭控制台,有时候它没有错误(在控制台中显示正确的&#34; SELECT&#34;),有时它得到了NameError信息。然后我发出了 rails restart 命令,从那时起,我得到了NameError。

感谢您的帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

检查您的架构.rb,此处型号名称为transactiontypestransactions。因此,您无需在self.table_name = "transactiontypes"self.table_name = "transactions"上添加transactiontypes.rbtransactions.rb。而不仅仅是改变 app / models / admin 文件夹:

transactiontype.rb:

module Admin
  class Transactiontype < ApplicationRecord
    has_many :transactions
  end
end

transaction.rb:

module Admin
  class Transaction < ApplicationRecord
    belongs_to :transactiontype
  end
end

现在你可以试试rails console:

Admin::Transactiontype.all