has_one 关系如果超过一个自动设置为零

has_one relation automatically set nil if more than one

给出两个模型,具有has_one关联:

class ShopInfo
  belongs_to :shop
end

class Shop
  has_one :shop_info
end


s = Shop.create
ss1 = s.create_shop_info

在我的代码的其他地方

ss2 = s.create_shop_info 

在此之后,ss1.shop_id 被设置为 nil,因此 ss1 现在是一个孤立记录。

有什么方法可以删除以前的记录而不是将它们设置为零吗?

Fran,如果你看the has_one documentation,我想你想使用association=方法:

association=(associate)

Assigns the associate object, extracts the primary key, sets it as the foreign key, and saves the associate object. To avoid database inconsistencies, permanently deletes an existing associated object when assigning a new one, even if the new one isn't saved to database.

这意味着您的代码可能看起来像...

ss2.shop_info = ShopInfo.new(...)

默认情况下,has_one 关联执行 nullify。添加 dependent: :destroy 解决了问题。

class Shop
  has_one :shop_info, dependent: :destroy
end

如果有人需要更多信息,has_one 替换记录的 ActiveRecord 代码是这样的:

https://github.com/rails/rails/blob/v4.2.6/activerecord/lib/active_record/associations/has_one_association.rb#L24-L51

但是如果在关联中添加 dependent 选项,也会执行 delete 方法:

https://github.com/rails/rails/blob/v4.2.6/activerecord/lib/active_record/associations/has_one_association.rb#L7-L22