5

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

Community
  • 1
  • 1
gmoniey
  • 7,975
  • 4
  • 27
  • 30

2 Answers2

3

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
mockaroodev
  • 2,031
  • 1
  • 20
  • 24
1

You can add config/environments/development.rb:

Dir[Rails.root.join('app', 'models', '**/*')].each { |file| File.basename(file, '.rb').camelize.constantize }
vad4msiu
  • 11
  • 1
  • Yea...I was already doing that, but its a hack...I filed a ticket here: https://github.com/rails/rails/issues/5148 – gmoniey Apr 10 '12 at 02:11
  • this doesn't work with namespaced models, i do not think. have you ever run into a namespaced usecase? – jay Mar 13 '14 at 10:13