How can I force Rails to load all models?

后端 未结 2 1811
悲哀的现实
悲哀的现实 2021-01-04 02:26

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 wi

2条回答
  •  时光说笑
    2021-01-04 02:45

    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
    

提交回复
热议问题