Starkers
Starkers

Reputation: 10551

Programmatically query a database table via active record in a rake task

I am making a rake task:

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

Now, despite having an instance string of "Type" (on the first loop), I can't use it to programtically query the database. Constants can't be evaluated in the same way that instance variables and local variables can, it seems. How can I Programmatically an array of column names?

Upvotes: 0

Views: 310

Answers (1)

tihom
tihom

Reputation: 8003

try t.classify.constantize it returns Type as a class on which you can call the method column_names or any other class method.

Read more about classify and constantize

Upvotes: 1

Related Questions