How to find a model class from its table name?

Viewed 11600

This question is reverse of this question: How to determine table name within a Rails 3 model class .

My intention is to look at Rails project database and try to figure out all possible model classes the project is related to. I have few clues, such as to get table name list from AR connection, etc. But down to table_name -> model class mapping. I got no idea.

Thanks.

4 Answers

How about:

def index_by_table_name
  @index_by_table_name ||= ActiveRecord::Base.descendants.reject(&:abstract_class).index_by(&:table_name)
end

klass = index_by_table_name[table_name]

The better way, is to go the other way around, load all models and extract their table names.

Rails 6.x / Zeitwerk

# load all clases
Zeitwerk::Loader.eager_load_all

# get all named classes extending ApplicationRecord
all_models = ObjectSpace.each_object(Class).select { |c| c < ApplicationRecord}.select(&:name)

# build the index
model_by_table_name = all_models.index_by(&:table_name)
Related