Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ActiveRecord table name to model class name

Is there any possibility to properly convert ActiveRecord table name to model class name? I have found one hack

def model_for_table(table_name)
  table_name.classify.constantize
end

but since we use set_table_name for many of our models this wont work. Is there any way to do it?

like image 773
lzap Avatar asked May 26 '11 15:05

lzap


3 Answers

I did it!

This returns a hash in the form of "table_name" => "model_class_name".

Hash[ObjectSpace.enum_for(:each_object, class << ActiveRecord::Base; 
    self; end).to_a.reject{|c| c == ActiveRecord::Base}.collect{
    |c| [c.table_name, c.name]}]

EDIT: Better version (works with Rails 3 only):

Hash[ActiveRecord::Base.send(:descendants).collect{|c| [c.table_name, c.name]}]

Please note not all your model classes are always loaded. To load them all before creating such a hash do this:

Dir.foreach("#{RAILS_ROOT}/app/models") { |f| require f if f =~ /.*\.rb/ }

Nice.

like image 139
lzap Avatar answered Oct 14 '22 21:10

lzap


ObjectSpace.each_object(Class).select{ |klass| 
  klass < ActiveRecord::Base 
}.index_by(&:table_name)

It is not the fastest thing in the world though

like image 2
Victor Moroz Avatar answered Oct 14 '22 21:10

Victor Moroz


Can do like this in rails 3:

ActiveRecord::Base.descendants.collect{|c| [c.table_name, c.name]}
like image 1
magicxman Avatar answered Oct 14 '22 20:10

magicxman