2011-01-13 33 views
3

我正在使用faker生成示例數據。我有這個如下:Rails 3:生成僞造數據以填充DB

require 'faker' 

namespace :db do 
    desc "Fill database with sample data" 
    task :populate => :environment do 
    Rake::Task['db:reset'].invoke 
    User.create!(:name => "rails", 
    :email => "[email protected]", 
    :password => "foobar", 
    :password_confirmation => "foobar") 

    99.times do |n| 
     #name = Faker::Name.name 
     name = "rails#{n+1}" 
     email = "example-#{n+1}@railstutorial.org" 
     password = "password" 
     user = User.create!(:name => name, 
     :email => email, 
     :password => password, 
     :password_confirmation => password) 

    end 
    end 
end 

的問題是,我有一對夫婦在創建用戶時不被稱爲after_save的回調。這是爲什麼?由於

的方法:

after_save :create_profile 
def create_profile 
    self.build_profile() 
    end 
+0

推薦您張貼在模型中after_save的回調部分(包括方法和回調) – 2011-01-13 20:32:06

+0

你想,而不是使用觸發器,覆蓋保存方法?我是新來的鐵軌,所以我不知道這是否是一種反模式練習...... :) – 2011-01-13 20:41:58

回答

-3

在我所有的閱讀,似乎save!繞過已定義的任何定製before_saveon_saveafter_save過濾器。 create!的源代碼顯示它調用save!。除非你絕對需要爆炸版本,你爲什麼要使用它?嘗試刪除所有的爆炸方法,只是調用非爆炸版本:

[1..100].each do |n| 
    name = "rails#{n+1}" 
    email = "example-#{n+1}@railstutorial.org" 
    password = "password" 
    user = User.new(:name => name, :email => email, :password => password, :password_confirmation => password) 

    if !user.save 
    puts "There was an error while making #{user.inspect}" 
    end 
end