有一个

has_one 关联与另一个模型建立一对一的连接,但具有不同的语义。此关联表示模型的每个实例包含或拥有另一个模型的一个实例。

例如,如果应用程序中的每个用户只有一个帐户,则你将声明用户模型如下:

class User < ApplicationRecord
  has_one :account
end

在 Active Record 中,当你具有 has_one 关系时,活动记录可确保外键中只存在一条记录。

在我们的示例中:在 accounts 表中,只能有一个具有特定 user_id 的记录。如果你尝试为同一用户关联另一个帐户,则会将上一个条目的外键设为 null(使其成为孤立)并自动创建一个新帐户。即使新条目的保存失败以保持一致性,它也会使前一个条目为 null。

user = User.first
user.build_account(name: "sample")
user.save   [Saves it successfully, and creates an entry in accounts table with user_id 1]
user.build_account(name: "sample1")  [automatically makes the previous entry's foreign key null]
user.save  [creates the new account with name sample 1 and user_id 1]