How to convert ActiveRecord table name to model class name

这一生的挚爱 提交于 2019-12-18 14:43:53

问题


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?


回答1:


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.




回答2:


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

It is not the fastest thing in the world though




回答3:


Can do like this in rails 3:

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


来源:https://stackoverflow.com/questions/6140932/how-to-convert-activerecord-table-name-to-model-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!