在rake种子的嵌套属性上获取父ID

时间:2015-10-20 13:17:25

标签: ruby-on-rails

我正在尝试设置这样的种子:

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,就像我在这里一样?

1 个答案:

答案 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!