我正在使用 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
最佳答案
在我所有的阅读中,save!
似乎绕过了任何自定义的 before_save
、on_save
或 after_save
过滤器你已经定义了。 create!
的源代码显示它调用了 save!
。除非你绝对需要 bang 版本,否则你为什么要使用它?尝试删除所有 bang 方法并只调用非 bang 版本:
[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
关于ruby-on-rails - rails 3 : Generate Fake Data to Populate DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4683664/