我正在 Rails 中创建用户及其个人资料之间的关系,如下所示
User has_one :profile
Profile belongs_to :user
据我所知,正常情况下Rails会自动创建这两个模型之间的外键关系。但是,当我通过以下方式使用信息播种数据库时,创建了许多用户并创建了许多配置文件,那么我如何确保例如 Joe 的配置文件与 Joe 的用户帐户链接。
User.create!(email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab09abdb7bbb3b6f4b9b5b7" rel="noreferrer noopener nofollow">[email protected]</a>", password: "blahblah", encryptedpass: "3838")
Profile.create!(first_name: "Joe", last_name: "Frank", address: "43 Flint Road", phone: "604 345 678", )
User.create!(email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771619191237101a161e1b5914181a" rel="noreferrer noopener nofollow">[email protected]</a>", password: "blahblahblah", encryptedpass: "4567")
Profile.create!(first_name: "Anna", last_name: "Jones", address: "43 Boogy Road", phone: "604 345 678", )
...想象一下成千上万的用户和个人资料以这种方式播种...
我是否必须在个人资料上设置 user_id
外键,并且为了播种它,我是否只需编写一个外键 ID? Rails 可以为我生成它吗?例如,如果我在 Joe 的个人资料上创建了一个外键 user_id: 1
我如何确定他的用户模型实例将为“1” 换句话说,如果我手动设置他的 user_id外键,如何确保它与用户模型的 id 匹配?
最佳答案
您可以使用create_profile!
method (当您声明 has_one :profile
u = User.create!(email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91fbd1f6fcf0f8fdbff2fefc" rel="noreferrer noopener nofollow">[email protected]</a>", password: "blahblah", encryptedpass: "3838")
u.create_profile!(first_name: "Joe", last_name: "Frank", address: "43 Flint Road")
关于ruby-on-rails - 在 Rails 中播种外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14466259/