Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
Juguang Avatar asked Dec 07 '13 07:12

Juguang


2 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]
like image 114
Scott Avatar answered Oct 12 '22 22:10

Scott


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
like image 36
Austin Lin Avatar answered Oct 13 '22 00:10

Austin Lin