Question

I want to populate my database with test data my user and profile models are seperate form each other with a 1-to-1 relationship. The script that I'm running creates the data but doesn't relate it together. how would I get it to related the data together?

app/models/user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_one :profile

  attr_accessible :email, :password, :password_confirmation, :remember_me,      :profile_attributes


 accepts_nested_attributes_for :profile

end

app/models/profile.rb

class Profile < ActiveRecord::Base
   belongs_to :user

   attr_accessible :first_name, :last_name

   validates :first_name, presence: true
   validates :last_name, presence: true

end

lib/tasks/sample_data.rb

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
   User.create!(email: "dufall@iinet.net.au",
             password: "123qwe",
             password_confirmation: "123qwe")
   Profile.create!(first_name: "Aaron",
                last_name: "Dufall")
   99.times do |n|
   first_name  = Forgery::Name.first_name
   Last_name  = Forgery::Name.last_name
   email = "example-#{n+1}@railstutorial.org"
   password  = "password"
   User.create!(email: email,
                password: password,
                password_confirmation: password)
  Profile.create!(first_name: first_name,
                  last_name: Last_name)
  end 
 end
end
Was it helpful?

Solution

Try to use user.create_profile! instead of Profile.create!

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
   user = User.create!(email: "dufall@iinet.net.au",
             password: "123qwe",
             password_confirmation: "123qwe")
   user.create_profile!(first_name: "Aaron",
                last_name: "Dufall")
   99.times do |n|
     first_name  = Forgery::Name.first_name
     Last_name  = Forgery::Name.last_name
     email = "example-#{n+1}@railstutorial.org"
     password  = "password"
     user = User.create!(email: email,
                password: password,
                password_confirmation: password)
     user.create_profile!(first_name: first_name,
                  last_name: Last_name)
  end 
 end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top