如何ActiveRecord的表名转换为模型类名转换为、模型、ActiveRecord

2023-09-09 22:12:07 作者:自嘲自闹自疯癫

是否有可能适当地转换ActiveRecord的表名到模型类的名称?我已经找到了一个破解

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

但由于我们使用set_table_name我们许多型号的这不会工作。有没有办法做到这一点?

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

推荐答案

我做到了!

这将返回一个哈希在表格名=>model_class_name。

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]}]

编辑:更好的版本(适用于Rails的3只):

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/ }

尼斯。