Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
scotchi Avatar asked Jul 14 '10 12:07

scotchi


People also ask

What is eager loading rails?

Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use. Gotcha!

Does every model need a controller rails?

Do I need a controller for each model? No, not necessarily. However, having one controller per RESTful resource is a convention for a reason, and you should carefully analyze why that convention isn't meeting your needs before doing something completely different.

What do models do in Rails?

A Rails Model is a Ruby class that can add database records (think of whole rows in an Excel table), find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD--Create, Remove, Update, Destroy.


2 Answers

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!

like image 123
DSimon Avatar answered Sep 23 '22 21:09

DSimon


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
like image 44
tig Avatar answered Sep 23 '22 21:09

tig