Topic: Rake and ActiveRecord

I am wanting to run a rake task to load starter information into my tables. I was wanting to be able to call the task like rake db:load_data MODEL=Products. I think I have it working, except I can't seem to translate from a string to a class name. (See each line that has 'model' in it. Does anybody know how to do this?

require 'yaml'

namespace :db do

  desc "Populate a table with starter data"
  task :load_data => :environment do
    puts "Loading data"
    model = ENV['MODEL']
    file_name = ENV['MODEL'].downcase
    data = YAML::load(ERB.new(File.read("#{RAILS_ROOT}/db/fixtures/#{file_name}.yml")).result)
    data.each do |d|
      #http://railspikes.com/2008/2/1/loading-seed-data
      record = model.find_by_id(d.id) || new
      record.attributes = d
      record.save!
      record
    end
  end

end

Re: Rake and ActiveRecord

ActiveSupport provides #constantize (http://api.rubyonrails.com/classes/Acti … ml#M000488), which I think is what you need.

"Product".constantize # => Product
Ryan Heneise  |  Art of Mission  |  Now with extra-strong Donor Tools mojo