Home > front end >  How to access ApplicationRecord inside initializer script?
How to access ApplicationRecord inside initializer script?

Time:11-14

Is there any way to access ApplicationRecord and its models inside an initialization script? Like:

# config/initializers/start.rb
include ApplicationRecord

User.all.each do |user|
  # do stuff with users
end

CodePudding user response:

There is no guarantee your initializer in config/initializers will be executed after all gems' initializers, so if your initializer relies on ActiveRecord fully initialized (or any other moving part of the application) you'd better put the code into config.after_initialize block. The documentation is quite explicit with regards to that.

CodePudding user response:

Thanks to @Konstantin Strukov, that's how I ended up doing

# config/initializers/start.rb
Rails.application.config.after_initialize do
  User.all.each do |user|
    # do stuff with users
  end
end
  • Related