首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails:用rake和forgery填充嵌套模型

Rails:用rake和forgery填充嵌套模型
EN

Stack Overflow用户
提问于 2012-06-17 20:46:19
回答 1查看 385关注 0票数 0

我想用测试数据填充我的数据库,我的用户模型和配置文件模型是以1对1的关系彼此分离的。我正在运行的脚本创建数据,但不将它们关联在一起。我怎样才能把这些数据关联起来呢?

app/model/user.rb

代码语言:javascript
复制
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/model/profile.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-17 21:10:30

尝试使用user.create_profile!不是Profile.create!

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11071389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档