How can I force Rails to load all models?
Rails does model loading on demand. For a rake task that I'm writing, I need to be able to iterate over all ActiveRecord::Base
instances (which is possible with ActiveRecord::Base.send(:subclasses)
).
However, for the above to work, they have to already be loaded. Anyone know of a way开发者_高级运维 to force all models to load? Ideally I'd like to not have to poke through app/models
since I'd like to catch models added by plugins as well.
I needed all models loaded for a rake task that checks the validity of all records, and found the handy method eager_load
, which can be used simply like so:
Rails.application.eager_load!
rails 2:
Dir[Pathname(RAILS_ROOT) + 'app/models/**/*.rb'].each do |path|
require path
end
rails 3:
Dir[Rails.root + 'app/models/**/*.rb'].each do |path|
require path
end
another way:
(ActiveRecord::Base.connection.tables - %w[schema_migrations]).each do |table|
table.classify.constantize rescue nil
end
rails 7.0
Rails.initialize!
Will actually load all the models and anything you could need.
Works fine for .rake
files (rails cli commands) too.
精彩评论