我在使用实际模型时遇到问题,在尝试创建用户时出现以下错误:
app/models/user.rb:1:in `<top (required)>': uninitialized constant ApplicationRecord (NameError)
我在models/application_record.rb 中确实有以下文件
看起来像:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
当我将User类改为从ActiveRecord::Base继承时,除了ActiveRecord之外,我得到了相同的错误。
我的应用程序.rb:
class Application < Rails::Application
config.load_defaults 6.1
config.generators.system_tests = nil
end
我使用的是Rails 6.1。
我的Gemfile:
ruby '2.6.3'
gem 'activerecord'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
gem 'rails', '~> 6.1.4'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 5.0'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 5.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.4', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 4.1.0'
# Display performance information such as SQL time and flame graphs for each request in your browser.
# Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md
gem 'rack-mini-profiler', '~> 2.0'
gem 'listen', '~> 3.3'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
发生了什么?我没有拼写错误,模型是user.rb,我不知道发生了什么。
我找到的所有建议
因此,如果有人遇到这个问题,并且您有所需的文件,请检查是否正在加载rails环境。我补充道:
require "#{File.dirname(__FILE__)}/config/environment.rb"
到我运行的文件顶部,在那里我调用了类,这解决了问题。