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.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With