How to convert ActiveRecord table name to model class name

前端 未结 3 445
小蘑菇
小蘑菇 2021-01-01 19:55

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.         


        
相关标签:
3条回答
  • 2021-01-01 20:02

    Can do like this in rails 3:

    ActiveRecord::Base.descendants.collect{|c| [c.table_name, c.name]}
    
    0 讨论(0)
  • 2021-01-01 20:05
    ObjectSpace.each_object(Class).select{ |klass| 
      klass < ActiveRecord::Base 
    }.index_by(&:table_name)
    

    It is not the fastest thing in the world though

    0 讨论(0)
  • 2021-01-01 20:25

    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.

    0 讨论(0)
提交回复
热议问题