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.
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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With