ruby-on-rails - rails 3 : Generate Fake Data to Populate DB

标签 ruby-on-rails ruby-on-rails-3 rubygems rspec2

我正在使用 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_saveon_saveafter_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/

相关文章:

ruby-on-rails - 为什么此devise_group调用会出现NoMethodError?

ruby-on-rails - 在没有互联网可用性的情况下安装 gem

ruby-on-rails - 错误 : rails aborted! LoadError : dlopen(/Users. ..但是是一个不兼容的架构(有 'x86_64' ,需要 'arm64e' ))

ruby-on-rails - rails-如何将路线映射到多个模型

ruby-on-rails-3 - "413 Request Entity Too Large"错误 Rails 3.2 乘客 Phusion

javascript - 在 Rails 应用程序和 Node.js 应用程序之间进行通信

ruby-on-rails - Rails 找不到 gem

Mac Lion 10.7 上的 MySQL 错误

ruby-on-rails - Rails 3 - 在任何来源中都找不到 rake-0.9.2 (Bundler::GemNotFound)

ruby - 如何使用 Middleman 显示 Gravtar?