Monday, 19 August 2013

Listing all columns in all models

As I look to upgrade to Rails 4, and I am looking at strong parameters - more on them later - but something I need on the way is a list of columns for each model. Here is some code that will do that.

First, make sure all your models are loaded (this can take some time) (cache_classes must be on, which it is by default in development mode):


Then get an array of all  ActiveRecord::Base sub-classes. It also get sub-classes of sub-classes, by the way.

ary = ActiveRecord::Base.descendants

Then you just need to list them:

puts {|m| "#{m.to_s} ~ :#{m.column_names.join ', :'}" }.join("\n")

Here is a useful page about preparing the upgrade to Rails 4, by the way:

No comments: