Brian Postow
Brian Postow

Reputation: 12187

NameError: uninitialized constant ApplicationRecord

I'm getting the above error, but I believe that I using 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)

I don't think that the --trace is useful... but can attach it if desired...

Upvotes: 3

Views: 3838

Answers (2)

max
max

Reputation: 101821

Prior to version 5 Rails generated models that inherited from ActiveRecord::Base.

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

end

Rails 5 introduced ApplicationRecord which is the model equivalent to ApplicationController. So on Rails 5 the following is generated:

# rails g model foo.
class Foo < ApplicationRecord

end

The ApplicationRecord class itself is generated when you run rails new.

However there is nothing magical about it - its just a superclass thats engrained in the conventions.

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

If you are getting NameError: uninitialized constant ApplicationRecord you either upgraded to Rails 5 without creating it or deleted it by mistake. The solution is simply to create the file.

Upvotes: 4

ErvalhouS
ErvalhouS

Reputation: 4216

You have two options, you either change app/models/client.rb class declaration to:

class Client < ActiveRecord::Base

Or alternatively you can create a app/models/application_record.rb file with the contents:

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

Upvotes: 4

Related Questions