I know that you can do something like this to load the rails environment:
task :my_task => :environment do
MyModel.find(1)
end
But it seems the code in the models are not executed. I am using acts_as_audited, and there is a nice class function which retrieves all models which are being audited. The call looks something like:
Audit.audited_classes
And to specify a model as being auditable, you simply add this line to your models:
acts_as_audited
When audited_classes is executed in console, I get an array of all my audited classes; however, when I execute it from within a rake task (or migration), I get an empty array.
[EDIT]
After playing around a bit more, I noticed that if the models are not actually loaded until they are referenced (i.e. lazy loading). I thought that setting cache_classes to true in the config would fix this, but they still seem to be lazy loaded.
One possible solution would be to loop through all the models (as explained in this post: Is there a way to get a collection of all the Models in your Rails app?) but that seems a bit hacky, and I was hoping there is a cleaner way.
Any ideas?
Thanks
This happens when you have config.threadsafe! in production environments, which automatically sets config.dependency_loading = false. This prevents rails from loading your model classes during rake tasks.
The way to get around this is to set "config.dependency_loading = true if $rails_rake_task" in your environment file. For example, in my production.rb I have:
config.threadsafe!
config.dependency_loading = true if $rails_rake_task
or you can also do
config.threadsafe! unless $rails_rake_task
You can add config/environments/development.rb:
Dir[Rails.root.join('app', 'models', '**/*')].each { |file| File.basename(file, '.rb').camelize.constantize }
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