贴一段 rails guides 的讲解
When you assign an object to a
has_oneassociation, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
If either of these saves fails due to validation errors, then the assignment statement returns
falseand the assignment itself is cancelled.
If the parent object (the one declaring the
has_oneassociation) is unsaved (that is,
true) then the child objects are not saved. They will automatically when the parent object is saved.
If you want to assign an object to a
has_oneassociation without saving the object, use the
class User < ApplicationRecord has_one :wallet, dependent: :destroy # 一个【用户】对于一个【钱包】 before_create :create_default_wallet def create_default_wallet build_wallet # 相当于 new 了一个【钱包】 true end # 【用户】创建成功后，对应的【钱包】才 save end