How to do populate task? I'm trying something like...

I’m trying to write a taks to populate my rails project with Users.

I wrote a simple script to generate and construct a yaml file, like it:

#!/usr/bin/ruby

require ‘digest/sha1’

letras = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘x’, ‘z’]

def sort
return Kernel.rand(23)
end

def password
pass = sort.to_s + sort.to_s + sort.to_s
return Digest::SHA1.hexdigest(pass)
end

file = File.new(‘populate.yml’, ‘w’)

10.times do |i|
name = letras[sort].upcase + letras[sort] + letras[sort] + letras[sort]
file.puts name + ‘:’
file.puts ’ ’ + ‘id:’ + ’ ’ + i.to_s
file.puts ’ ’ + ‘name:’ + ’ ’ + name

file.puts ’ ’ + ‘email:’ + ’ ’ + name.downcase + ‘@’ + ‘dom.com
file.puts ’ ’ + ‘hashed_password:’ + ’ ’ + password

file.puts ’ ’ + ‘nickname:’ + ’ ’ + name
end

The ouput:

Hhpd:
id: 0
name: Hhpd
email: hhpd@dom.com
hashed_password: bdd9ab67b021794754b0bf856a9bc728c1a3e968

nickname: Hhpd
Jmzs:
id: 1
name: Jmzs
email: jmzs@dom.com
hashed_password: 70bc993e97958abc9f223c94e94742065d15efd8
nickname: Jmzs
Dpqv:
id: 2

name: Dpqv
email: dpqv@dom.com
hashed_password: e816958259e39339ddc56994e959aa56ef874f92
nickname: Dpqv

That’s ok. But now how can i get the yaml file and insert it on database using ActiveRecord? I tried to do:

require ‘active_record’
require ‘active_record/fixtures’

namespace :db do
DATA_DIRECTORY = “#{RAILS_ROOT}/lib/tasks/populate”
namespace :populate do
desc ‘ghost users’

task :load => :environment do |t|
  class_name = 'User'
  table_name = 'Users'
  fixture = Fixtures.new(ActiveRecord::Base.connection,
                         table_name, class_name,

                         File.join(DATA_DIRECTORY, table_name.to_s))
  fixture.insert_fixtures
  puts "that's right"
end

end
end

What’s wrong? I’m seeing the development.log and none is INSERTED in database.

Thank you very much to ready this question!

Since your default users are just for testing, put them into test/
fixtures and do rake db:fixtures:load

If you want to write the rake task just for the fuck of it, i did it
this way

namespace :db do
  namespace :fixtures do
    desc "load default fixtures from db/defaults/*"
    task :defaults => :environment do
      require "active_record/fixtures"
      ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
      puts "Fixtures"
      Dir.glob(File.join(RAILS_ROOT, 'db', 'defaults', '*.{yml,
csv}')).each do |fixture_file|
        Fixtures.create_fixtures('db/defaults',
File.basename(fixture_file, '.*'))
        puts "* #{fixture_file}"
      end
      puts "succesfully loaded"
    end
  end
end

code takes everything from db/defaults ending in yml and loads it into
current environment. Its almost completely the same as original rake
db:fixtures:load task.