0

我正在做一个 rake 任务:

task :populate => :environment do
    table_array = ActiveRecord::Base.connection.tables #=> ["types","products"]

    table_array.each do |t|
        puts t

        instance_string = t.capitalize.singularize.to_s #=> "Type" (on the first loop)
        puts Type.column_names #=> ["id", "type_name", "created_at", "updated_at"]

        # This will return an error, undefined method 'column_names'
        puts "#{instance_string}".column_names
    end
end

现在,尽管有一个“类型”的实例字符串(在第一个循环上),但我不能用它来以编程方式查询数据库。似乎不能以与实例变量和局部变量相同的方式评估常量。如何以编程方式列名数组?

4

1 回答 1

1

尝试t.classify.constantizeType作为一个类返回,您可以在该类上调用该方法column_names或任何其他类方法。

阅读有关分类恒定化的更多信息

于 2013-09-28T07:50:39.213 回答