Neat little snippet of code in those odd times you need to loop over every model in your application programmatically.
This exact snippet loops over every model, and converts each timestamp (created_at, updated_at) to UTC. It can be quite helpful if you're adding Time Zone support to your Rails 2.1 application and you have existing non-UTC timestamps.
all_models = Dir.glob( File.join( RAILS_ROOT, 'app', 'models', '*.rb') ).map{|path| path[/.+/(.+).rb/,1] }
ar_models = all_models.select{|m| m.classify.constantize < ActiveRecord::Base}
*Please note: I haven't tested this very thoroughly, but it does seem to do the trick. As we know, Dates and Times can be total PITAs!














Matt, I was about to write this exact same utility so I could add time zone support to my site, and I see you’ve already done it! Thanks, this is great!
Hey Matt,
Tried your snip and it seems to only dump cached models.
# bw: hijacked from http://blog.matt-darby.com/2008/05/16/iterating-over-all-models-in-rails/
# Thanks, Some Internet Guy
def self.all_models
klasses = []
Object.constants.each do |o|
klass = eval(o, TOPLEVEL_BINDING)
if klass.is_a?(Class) && klass.superclass == ActiveRecord::Base
klasses > ActiveRecordHelpers.all_models
=> [CachedModel, Treeitem]
if called after accessing another object:
>> t = Treeitem.find :first
=> #
>> t.space
=> #
>> ActiveRecordHelpers.all_models
=> [CachedModel, Space, Treeitem]
Hmm….