NameError:未初始化的常量ApplicationRecord

时间:2019-04-25 16:56:00

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

我遇到上述错误,但我相信我使用的是Rails 5:

turlingdrome$ rails -v
/Users/brianp/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/app_loader.rb:53: warning: Insecure world writable dir /Users/brianp/work in PATH, mode 040777
Rails 5.2.0

turlingdrome$ rake db:migrate
rake aborted!
NameError: uninitialized constant ApplicationRecord
/Users/brianp/work/online-reporting/app/models/client.rb:1:in `<top (required)>'
/Users/brianp/work/online-reporting/config/routes.rb:7:in `block in <top (required)>'
/Users/brianp/work/online-reporting/config/routes.rb:1:in `<top (required)>'
/Users/brianp/work/online-reporting/config/environment.rb:5:in `<top (required)>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)

我不认为--trace有用...但是可以根据需要附加它...

2 个答案:

答案 0 :(得分:1)

您有两个选择,您可以将Companies类声明更改为:

app/models/client.rb

或者,您也可以创建一个包含以下内容的class Client < ActiveRecord::Base 文件:

app/models/application_record.rb

答案 1 :(得分:0)

第5版之前,Rails生成的模型继承自ActiveRecord::Base

# rails g model foo.
class Foo < ActiveRecord::Base

end

Rails 5引入了ApplicationRecord,该模型等效于ApplicationController。因此在Rails 5上会生成以下内容:

# rails g model foo.
class Foo < ApplicationRecord

end

运行rails new时会生成ApplicationRecord类本身。

但是,这没有什么神奇的-它只是根深蒂固的惯例。

# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

如果您获得NameError: uninitialized constant ApplicationRecord,则要么升级到Rails 5而不创建它,要么误删除了它。解决方案就是创建文件。