0
테스트 데이터로 데이터베이스를 채우고 싶습니다. 사용자 및 프로필 모델이 서로 1 대 1 관계로 서로 분리되어 있습니다. 실행중인 스크립트는 데이터를 만들지 만 함께 연결하지는 않습니다. 데이터를 함께 연결하려면 어떻게해야합니까?레일 : 중첩 모델을 갈퀴와 위조로 채우기
응용 프로그램/모델/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 및 docs http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html – dimuch