Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Migration & Rake tasks not loading models?

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

like image 665
gmoniey Avatar asked Oct 15 '22 02:10

gmoniey


2 Answers

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
like image 91
mockaroodev Avatar answered Oct 20 '22 08:10

mockaroodev


You can add config/environments/development.rb:

Dir[Rails.root.join('app', 'models', '**/*')].each { |file| File.basename(file, '.rb').camelize.constantize }
like image 22
vad4msiu Avatar answered Oct 20 '22 08:10

vad4msiu