In the rails development environment, cache_classes is off so you can modify code under app/ and see changes without restarting the server.
In all environments, though, middleware is only created once. So if I have middleware like this:
class MyMiddleware
def initialize(app)
#app = app
end
def call(env)
env['model'] = MyModel.first
end
end
and I do this in config/environments/development.rb:
config.cache_classes = false # the default for development
config.middleware.use MyMiddleware
then I'll always get the following error:
A copy of MyMiddleware has been removed from the module tree but is still active!
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:414:in `load_missing_constant'
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:96:in `const_missing'
/Users/me/projects/my_project/lib/my_middleware.rb:8:in `call'
/Library/Ruby/Gems/1.8/gems/actionpack-2.3.2/lib/action_controller/middleware_stack.rb:72:in `new'
...
The problem is that the MyMiddleware instance is created once at system load time, but the MyModel class is reloaded on each call.
I tried 'MyModel'.constantize.first to delay binding to the class until method-call-time, but that changes the problem to a new one:
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.include?
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.2/active_record/attribute_methods.rb:142in `create_time_zone_conversion_attribute?'
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.2/active_record/attribute_methods.rb:75:in `define_attributes_methods'
...
This appears to be a Rails bug. See if you can upgrade your Rails version to 2.3.4 or 2.3.5.
I believe this is the commit that fixed the problem. Original bug report is here.
We encountered a problem similar to yours some time ago. As far as I remember this could be remedied by setting time_zone in environment.rb to :utc. It was a while ago and I don't remember exactly the config parameter name or whether it was 'UTC' or :utc. Give it a try, maybe it'll help.
Related
We are getting this error on all local setups of our project(currently) when we call any method like:
belongs_to :abc
after_create :some_method
def some_method
if self.abc.saved_change_to_parent_id?
...
// or even self.abc.parent_id_before_last_save
end
It gives:
NameError (undefined local variable or method `first' for ActiveRecord::NullMutationTracker:Class):
app/models/model_name.rb:50:in `some_method'
Yes, there is not a full trace with rails internal file paths etc, i only get my project files trace. Maybe its some logger config issue, any help to get full trace will also be appreciated.
There are no such issues i could find on internet, thats why posting here.
PS: Not posted on rails issue tracker(github issues) because i don't have minimal reproduction.
Stack
ruby: 2.4.3
rails: 5.1.5 (also tried on 5.1.7)
OS: Ubuntu 20, also tried on macOS
Thanks in advance.
UPDATE1: Using byebug, i got to this trace, where error is occuring:
/Users/dev/.rvm/gems/ruby-2.4.3/gems/acts_as_singleton-0.0.8/lib/acts_as_singleton.rb:43
which is here, so it is not directly from rails, but a very outdated gem we have in our code for some reason.
As i posted in the update, issue was not with rails or anything, i used byebug to track trace and it was something like:
activemodel-5.1.5/lib/active_model/attribute_methods.rb:384
activerecord-5.1.5/lib/active_record/attribute_methods/dirty.rb:146
activerecord-5.1.5/lib/active_record/attribute_methods/dirty.rb:319
activerecord-5.1.5/lib/active_record/attribute_methods/dirty.rb:315
acts_as_singleton-859f49112c03/lib/acts_as_singleton.rb:43
The last line, should not be there, as we are not using acts_as_singleton on any of the involved models.
So after some tracking, it turned out issue with the gem. I have created a fork and used that fork. Here is the fork: https://github.com/ziaulrehman40/acts_as_singleton (forked it from another fork, which seemingly had some other fixes as well). And you can see my changes here.
What was the issue?
This gem writes a module named Singleton within ActiveRecord module. Which seems ok, unless you realize that there is another module named Singleton already. Whihc is being included in:
gems/activerecord-5.1.5/lib/active_record/attribute_mutation_tracker.rb:83
class NullMutationTracker # :nodoc:
include Singleton
...
So as you can see, this Singleton module gets overriden(or expanded, not sure) un-intentionally by that outdated gem(acts_as_singleton).
Unable to use rspec and rollbar after upgrading to rails 5.
Create a Rails 4 app
Upgrade gemfile to use rails 5
Try adding rollbar gem/support
Standard config/environment.rb:
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
Error when running rspec:
An error occurred while loading {path to specific spec file}
Failure/Error: require File.expand_path('../../config/environment', __FILE__)
RuntimeError:
can't modify frozen Array
# ./config/environment.rb:6:in `<top (required)>'
# ./spec/rails_helper.rb:5:in `<top (required)>'
...
No examples found.
In most cases, that error is a red herring for something else.
When encountering it, don't get overwhelmed with the recurrent can't modify frozen Array error messages, and instead check the very first error that appears when running a spec.
For example:
Failure/Error: validate :uniqueness, if: 'should_be_unique?'
ArgumentError: Passing string to be evaluated in :if and :unless
conditional options is not supported. Pass a symbol for an instance
method, or a lambda, proc or block, instead.
Just to add one tip on top of Maxximo Mussini's answer.
If anyone can't find the first error on the terminal, please try to run RSpec on one file, i.e. rspec spec/models/user_spec.rb
You should be able to find the root case.
In my case, I haven't updated my local .env variables that is required by User model
Hope it helps
Debugging this is not easy but one possible solution is simple. It could be a naming conflict with Rollbar, possibly something getting monkey-patched. If you're seeing this RuntimeError but not using Rollbar, see other answer.
Add a Module ("namespace" of your choice) around your app class definition in config/application.rb.
The module won't affect much. The only difference I could find is when printing out your app it will now appear as (that's how we found the fix vs a new working app):
<MyTestAPP::Application ...> instead of <Application ...>
Change:
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
end
To:
Module MyTestApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
end
end
I just pushed a Rails 4 application to a new production env and noticed the timestamp is showed with UTC zone. They have been shown correctly in all other environment with PST , the Application config.time_zone I set in application.rb.
Further triaging the problem, I discovered that, in production env, the timestamp attributed is of Ruby class Time, not ActiveSupport::TimeWithZone
my_record.start_at.is_a?(ActiveSupport::TimeWithZone)
=> false
But, in test env, the timestamp attributed is class ActiveSupport::TimeWithZone
my_record.start_at.is_a?(ActiveSupport::TimeWithZone)
=> true
This is the same code base, and the vm was cloned from test, so the software versions are the same. I checked the production.rb file and didn't see anythings that changes this behavior.
I had
require 'rails/all'
in application.rb which should load all active support modules at start of app
The rest of the application seems to be working fine, so other active support classes must be loaded. Can someone help me to find out what was missing or changed in this particular env?
Thanks.
Update:
I decided to change my production.rb setting one at a time and found out that this is caused by
config.eager_load = true
When I change this value to false -- the ActiveSupport timezone is working again.
.. but I still cannot explain why the behavior changes when the class is pre-loaded. Any ideas?
For some reason (probably an updated gem) Rails is logging all my SQL commands now. I run autotest and they are being spammed during tests also. How do I turn it off?
I tried add this to config/environments/test.rb but it didn't work. logger was already nil.
# ActiveRecord::Base.logger = nil
# ActiveRecord::Base.logger.level = 1
Rails 4.0.0
Ok I found it. This worked:
config.after_initialize do
ActiveRecord::Base.logger = nil
end
Another thing you can do is call this code at runtime, it doesn't need to be in a config file.
For example, if you put in your specific test case
# test/functionals/application_controller_test.rb for example
ActiveRecord::Base.logger = nil
It would work just as well, and this way you can toggle it at runtime. Useful if you only want to stifle a few lines of code or a block.
In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):
The line that writes to the log (in Rails 3.2.16, anyway) is the call to 'debug' in lib/active_record/log_subscriber.rb:50.
That debug method is defined by ActiveSupport::LogSubscriber.
So we can knock out the logging by overwriting it like so:
module ActiveSupport
class LogSubscriber
def debug(*args, &block)
end
end
end
I am trying to get the OAuth gem to work with Rails 3 and I'm running into this weird problem... (independent of the gem, I think I've run into this once before)
I have a controller called "OauthTestController", and a model called "ConsumerToken". The model looks like this.
require 'oauth/models/consumers/token'
class ConsumerToken < ActiveRecord::Base
include Oauth::Models::Consumers::Token
end
When I go to "/oauth_test/twitter", it loads the Oauth::Models::Consumers::Token module and I'm able to connect to twitter no problem. But the second time I try it (just refresh the /oauth_test/twitter url), it gives me this error:
NameError (uninitialized constant Oauth):
app/models/consumer_token.rb:4
app/models/twitter_token.rb:2
app/controllers/oauth_test_controller.rb:66:in `load_consumer'
Why is that? It has something to do with load paths or being in development mode maybe?
Try using require_or_load instead of require. That forces full load each time when in development and can sometimes help with this sort of issue.
Yeah it's something to do with being in development mode. Setting config.cache_classes = true in your development.rb get's it working (but is a pain in the ass)