Rails 3: creating fake data to populate the database

I use faker to create sample data. I have the following:

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

The problem is that I have a couple of after_save callbacks that are not called when creating the Account. Why is this? Thanks

Methods

  after_save :create_profile
def create_profile
    self.build_profile()
  end
+3
source share
1 answer

Throughout my reading, it seems to save!bypass any custom filters before_save, on_saveor after_savethat you have defined. The source code for create!shows what it calls save!. Why don't you use this version? Try to remove all your hacking methods and just call the versions without binding:

[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 
-3
source

Source: https://habr.com/ru/post/1785256/


All Articles