我正在使用faker来生成样本数据。我有以下内容:
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 => "example@railstutorial.org",
: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 :(得分:-3)
在我的所有阅读中,似乎save!
绕过了您定义的所有自定义before_save
,on_save
或after_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