Juguang
Juguang

Reputation: 651

How to find a model class from its table name?

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.

Upvotes: 18

Views: 14201

Answers (4)

estani
estani

Reputation: 26457

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)

Upvotes: 8

Scott
Scott

Reputation: 311

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]

Upvotes: 21

duykhoa
duykhoa

Reputation: 2302

Check the ruby API http://apidock.com/rails/String/constantize

The constantize method will convert your string to a constant

Because your table name like job_applications, you'll need convert it to "JobApplication", look for humanize, titleize or classify method that is supported also.

Upvotes: 2

Austin Lin
Austin Lin

Reputation: 2564

The method called to do this in Rails is #classify (http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-classify). If you can use Ruby (or Rails itself), just do the following:

"table_name".classify

or to actually get the class name:

"table_name".classify.constantize

Upvotes: 30

Related Questions