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!