Rails has_one构建关联会删除现有记录,即使新记录无效 [英] Rails has_one build association deletes existing record even if new record is not valid
问题描述
我已经看到,在Rails(至少是5.2.1)中,如果您有一个具有has_one与另一个模型的关联的模型,则会发生以下情况:
I have seen that in Rails (5.2.1 at least) if you have a model with a has_one association to another model, the following happens:
class Car < ApplicationRecord
has_one :steering_wheel
end
class SteeringWheel < ApplicationRecord
belongs_to :car
validate_presence_of :name
end
我有一个带方向盘的汽车对象.然后,我尝试像这样构建一个新的方向盘:
And I have an existing car object with a steering wheel. Then I try to build a new steering wheel like so:
car.build_steering_wheel
我尝试构建的新方向盘无效,因为我未设置name属性.没什么,Rails从数据库中删除了我现有的方向盘记录!我了解并依靠构建关联在建立新记录时删除现有记录,但在新记录无效时不会删除.
The new steering wheel I am trying to build is not valid because I did not set the name attribute. NEVERTHELESS, Rails has deleted my existing steering wheel record from the database! I understand and rely on build association deleting the existing record when building a new one, but not when the new record is not valid.
有人知道如何解决这个问题吗?我尝试在事务中回滚,独立创建方向盘记录,并且仅在有效时才执行car.steering_wheel =方向盘.
Anyone know how to get around this? I've tried rollback in a transaction, independently creating a steering wheel record and only doing car.steering_wheel = steering wheel if it's valid.. nothing works.
推荐答案
这是has_one关联的build_associated方法的规定功能.build_associated将删除现有的关联,无论正在构建的新关联是否有效.因此,如果在事务期间有任何您希望旧关联得以保留的情况,请不要使用build_associated.
This is the prescribed functionality of the build_associated method for has_one associations. build_associated will delete the existing association regardless of whether the new association being built is valid or not. Therefore, do not use build_associated at all if there is any circumstance during the transaction where you want the old association to persist.
这篇关于Rails has_one构建关联会删除现有记录,即使新记录无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!