开发者

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开发者_Go百科 it?


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.


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

It is not the fastest thing in the world though


Can do like this in rails 3:

ActiveRecord::Base.descendants.collect{|c| [c.table_name, c.name]}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜