NameError: uninitialized constant (rails) - Can't 'see' Models - ruby-on-rails

I've just recently stopped being able to access my Models in rails console - it's like they don't exist. I can only see the Helper files, like UserHelper.rb etc. The model files have not been changed or renamed.
I've checked the solutions in other similar threads - stopping or removing spring doesn't resolve the issue - like here NameError: uninitialized constant (rails)
The only thing I've managed to do that had any effect was to change config.eager_load = false to true in config/environments/development.rb - but this setting had always been false before.
Similarly, running Rails.application.eager_load! will load all models and make them useable, but this resets after I exit/reload rails console.
I'm running Rails v 4.2.8 in the amazon cloud9 IDE

Related

Cannot load database model in rails c production

aliyun Elastic Compute Service
app_danci#iZ2ze599ua4y0nvsppbmjhZ:~/myproject$ rails c -e production
Running via Spring preloader in process 13978
Loading production environment (Rails 5.1.4)
2.3.1 :001 > u = User.first
NameError: uninitialized constant User
from (irb):1
2.3.1 :002 > User.all
NameError: uninitialized constant User
from (irb):2
Why can I not see the model User?
You're probably missing something. I think you have a migration for a users table. Have you run rails db:migrate? If so, maybe you have just the table but you have not defined the class User?
class User < ApplicationRecord
end
or maybe is your class User defined inside a module?
The common error, one can make is not using appropriate nested Namespaces. If your models are defined under a namespace please use it in your console too. It can be called by using a qualifying names such as ::Namespace::Model. It is highly unlikely that rails console loads fine and can't seem to call the Rails Model. Hope this helps.

Rails: uninitialized constant just happen on production server

I have a class that I put inside lib/network:
module NetworkApi
class NetworkProxy
end
end
Then in another class, I referenced this class:
network_proxy = ::NetworkApi::NetworkProxy.new(params)
Everything runs normally on my development environment, but when I deploy to the server, I get an error at the above line with the message:
NameError: uninitialized constant NetworkApi::NetworkProxy
I don't know why this strange error happens. Please tell me why.
Note that Rails 5 disables autoloading after booting the app in production.
From the linked blog post:
In the rare situation where our application still needs autoloading in the production environment, we can enable it by setting up enable_dependency_loading to true as follows:
# config/application.rb
config.enable_dependency_loading = true
config.autoload_paths << Rails.root.join('lib')`

Autoload related race condition in Cucumber with AJAX requests

I'm using Cucumber with capybara-webkit for my app's integration tests on Ruby 2.0.0, Rails 4.1. A handful of test in my cucumber test suite unexpectedly began spitting out errors like this:
Circular dependency detected while autoloading constant UiValidators::ParameterFinder (RuntimeError)
/Users/kingp/.rvm/gems/ruby-2.0.0-p451#triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:484:in `load_missing_constant'
/Users/kingp/.rvm/gems/ruby-2.0.0-p451#triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:180:in `const_missing'
/Users/kingp/Projects/rails-triquest/app/controllers/contacts_controller.rb:2:in `<class:ContactsController>'
/Users/kingp/Projects/rails-triquest/app/controllers/contacts_controller.rb:1:in `<top (required)>'
/Users/kingp/.rvm/gems/ruby-2.0.0-p451#triquest/gems/activesupport-4.1.1/lib/active_support/dependencies.rb:247:in `require'
...
The error says 'circular dependency', but it is actually thrown at any time the Rails autoloader tries to load a constant that is already in its set of loaded constants. Typically this is indeed due to a circular dependency, but I'm pretty sure that's not the case in my app. A diff between the branch with the crashing test and the stable branch I forked from shows that the only changes are to coffeescript files, view templates, a migration, and the new cucumber features I was writing. I haven't touched any controller or model code.
I ended up inserting some logging code into the rails autoloader to help me figure out what's going on:
# Inserted at activesupport-4.1.1/lib/active_support/dependencies.rb:467
_thread_id_for_debug = Thread.current.object_id
STDERR.puts "*** #{loaded.count} #{from_mod} #{const_name} - #{_thread_id_for_debug}"
loaded is a set of paths to autoloaded code files, from_mod the context where the request came from, const_name the constant we're trying to load. Which all ultimately got me this, immediately before the crash:
*** 104 Object SitesController - 70180261360940
*** 105 Object ContactsController - 70180240113760
*** 105 SitesController UiValidators - 70180261360940
*** 105 Object UiValidators - 70180261360940
*** 105 UiValidators ParameterFinder - 70180261360940
*** 107 UiValidators ParameterFinder - 70180240113760
It looks like two threads are attempting to autoload the same constant. My guess is that the name of the constant is added to Rails' set of 'loaded' constants by the first thread before it has finished loading. The second thread can't resolve the constant (since the load hasn't finished yet), asks the autoloader to find it, and the autoloader raises when it sees the constant in its 'loaded' set.
At this point in the test, two controllers (SitesController and ContactsController) are responding to AJAX requests, launched nearly simultaneously.
I have found a way to work around the crash, by just including a reference to the module UiValidators::ParameterFinder ahead of the AJAX. But this seems fragile, and also not very elegant. Short of turning on eager loading for the test environment, is there any other way to avoid this problem?
I had the same problem (without Cucumber, just Capybara & Poltergeist). setting config.eager_load = true didn't even work for me (don't quite understand why not..).
I ended up using Spring and haven't had a circular dependency error since.
I have the same issue with Rails 4.1.4 when using Sidekiq. I assume that a race condition inside the threaded Sidekiq workers caused all kinds of hijinks when const_missing inside active_support was called.
In addition to make sure that my current environment would perform eager loading i.e. via config.eager_load = true I also had to add all components that my workers were using from the lib directory into config.eager_load_paths (via config.eager_load_paths += %W(#{config.root}/lib) inside config/application.rb).
This was necessary because I assume that setting config.eager_load = true only makes Rails eager load the contents of the app/ directory.
App::Application.config.eager_load_paths
=> [
[0] "/home/archive/releases/20140721180504/app/assets",
[1] "/home/archive/releases/20140721180504/app/controllers",
[2] "/home/archive/releases/20140721180504/app/helpers",
[3] "/home/archive/releases/20140721180504/app/mailers",
[4] "/home/archive/releases/20140721180504/app/models",
[5] "/home/archive/releases/20140721180504/app/services",
[6] "/home/archive/releases/20140721180504/app/workers"
]
The combination of both seemed to have helped with the issue.

Conflict between Rails Admin and Impressionist gems

I'm using the latest version of the Impressionist and Rails Admin gems, and wondering if anyone could shed some light on an annoying conflict I'm experiencing. The problem is roughly documented here - https://github.com/sferik/rails_admin/issues/1315, yet the vaguely described solution is not working for me. When I have the line is_impressionable in my Listing model, I get an error when starting my Rails server with rails s:
...rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/dynamic_matchers.rb:22:in `method_missing': undefined local variable or method `is_impressionable' for Listing(no database connection):Class (NameError)
If I first start the server, and then add the 'is_impressionable' line, everything works fine, so the problem only occurs during initialization. I don't fully understand the initialization process, so am not sure how to go about getting this to work.
I have tried moving all my rails_admin model configuration options to their respective models, rather than in the initializer, which had no effect. I also have the following line in my initializer:
config.included_models = [Listing,ListingImage,AllOtherModelsHere...]
I have tried adding single quotes around these model names, which results in the following errors, as described in the github issue here
[RailsAdmin] Could not load model Listing, assuming model is non existing. (undefined local variable or method `is_impressionable' for Listing(no database connection):Class)
Any ideas what else I can try to make these gems work together? I don't want to have to remove the is_impressionable line every time I want to restart the server or generate a migration...
Not sure if the same issue that I had but yet I will post what worked for me just in case someone struggles with this too:
Im on a ruby 2.1.5 project with rails 4.2.0 and among other gems I'm using rails admin.
I run into several weird problems trying to set this up. For instance if I added the is_impressionable call within one of my models for some reason the execution of that file stopped there and I started getting weird errors like any method declared below the is_impressionable failed with undefined error.
So what I end up doing was:
class MyModel < ActiveRecord::Base
include Impressionist::IsImpressionable
is_impressionable
end
So this solved my issue and now i can access #my_model_instance.impression_count as expected.
I changed every occurrence of Klass to 'Klass'.constantize in initializer.

FriendlyId: undefined method `use_slug?' for nil:NilClass

I am creating a new environment besides production. I copied all the configurations from my production environment, changing what needed to be changed.
As it is the servers do start, but when I do a query I get this exception:
NoMethodError (undefined method `use_slug?' for nil:NilClass):
vendor/gems/friendly_id-2.3.4/lib/friendly_id/active_record2/finders.rb:65:in `slugged?'
vendor/gems/friendly_id-2.3.4/lib/friendly_id/active_record2/finders.rb:43:in `finder_class'
vendor/gems/friendly_id-2.3.4/lib/friendly_id/active_record2/finders.rb:37:in `finder'
vendor/gems/friendly_id-2.3.4/lib/friendly_id/active_record2/finders.rb:32:in `method_missing'
vendor/gems/friendly_id-2.3.4/lib/friendly_id/active_record2/slugged_model.rb:149:in `find_one'
app/controllers/home_controller.rb:5:in `index'
The line in question does this:
#page = Page.find("home")
I am using FriendlyId 2.3.4, and Rails 2.3.4. The code is the same for the production environment, and it's working just fine there, so I'm not really sure on what's going on here...I could see that the line where the exception gets raised does
friendly_id_config.use_slug?
so for a reason I'm not aware of friendly_id_config is nil.
Thanks for any guidance on this problem
I found a workaround to this issue by loading the server using the production environment.
I was trying to use a 'preprod environment, and somehow FriendlyId didn't like that strange environment.
Load the app using RAILS_ENV=production and it worked fine.
Not a solution, but at least could move on...

Resources