我正在尝试设置这样的种子:
company = Company.create!( name: 'Hirthe-Ritchie',
time_zone: 'Stockholm',
users_attributes: [{
first_name: 'Demo',
last_name: 'Memo',
title: 'CEO',
email: 'demo@demo.com',
time_zone: 'Stockholm',
admin: true,
password: 'foobar',
activated: true,
activated_at: Time.zone.now,
reviewer_attributes: {
reviewer_user_id: # parent id
}
}]
)
现在我想要的是在reviewer_attributes上,使reviewer_used_id成为正在创建的用户的用户ID。
所以我的Reviewer模型中有user_id和reviewer_user_id,现在如何在嵌套属性中获取父ID,就像我在这里一样?
答案 0 :(得分:0)
您必须将代码拆分为相关对象之间的几个新/创建。请尝试以下方法:
user_attrs = {
first_name: 'Demo',
last_name: 'Memo',
title: 'CEO',
email: 'demo@demo.com',
time_zone: 'Stockholm',
admin: true,
password: 'foobar',
activated: true,
activated_at: Time.zone.now
}
user = User.new(user_attrs)
user.reviewer = user
company = Company.new(name: 'Hirthe-Ritchie', time_zone: 'Stockholm')
company.users << user
company.save!