0
我想用測試數據填充我的數據庫我的用戶和配置文件模型是以1對1關係彼此分離的形式。我正在運行的腳本會創建數據,但不會將它們關聯在一起。我如何獲得它將數據關聯在一起?Rails:使用耙和僞造填充嵌套模型
應用程序/模型/ 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
應用程序/模型/ 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
末
的lib /任務/ sample_data.rb
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
User.create!(email: "[email protected]",
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
這樣做的伎倆,謝謝。你能否指出我進一步閱讀的方向,爲什麼這是有效的? –
嘗試檢查導軌指南http://guides.rubyonrails.org/association_basics.html#has_one-association-referencel和文檔http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html – dimuch