Enum lookup table

My team recently found some utility from adding a small rake task that generates an active_record_enums lookup table with table, enum, value, and value_description as columns. We have a data team that runs reports against a follower db that were having to do this manually on their end.

After railsconf we were trying to think of ways we could start contributing to rails and wondered if this little script might be useful to others.

So then this is generated from all the enums across all models? As you mention about reporting – sounds pretty useful for this.

Yes. Here’s the whole thing as of right now:

  desc "update active_record_enums table"
  task update_enums: :environment do
    class ActiveRecordEnum < ApplicationRecord; end

    enum_map = ActiveRecord::Base.descendants.sort{ |a, b| a.name <=> b.name }.map { |k| [k.table_name, k.defined_enums] }.to_h
    enum_map.each_pair do |table, enums|
      next if enums.blank?

      puts table
      enums.each_pair do |enum, values|
        puts '-' * 30
        puts "#{enum}:"
        values.each_pair do |description, value|
          record = ActiveRecordEnum.find_or_initialize_by(table: table, column: enum, value: value)
          record.update!(value_description: description) unless record.value_description.presence == description
          puts "created/updated data enum record #{value}:#{description}"
      puts '_' * 30
      puts "\n"
1 Like

I suppose one thing this is missing is the ability to deal with removed values. I wonder if an ‘active’ or inverse ‘deprecated/decommissioned’ column would be useful. Then another pass could run through ActiveRecordEnum.all and compare to the enum_map to see if the enum still exists in the code.