我已经看到,在Rails(至少为5.2.1)中,如果您有一个具有has_one与另一个模型的关联的模型,则会发生以下情况:
class Car < ApplicationRecord
has_one :steering_wheel
end
class SteeringWheel < ApplicationRecord
belongs_to :car
validate_presence_of :name
end
我有一个带方向盘的汽车对象。然后,我尝试像这样构建一个新的方向盘:
car.build_steering_wheel
我尝试构建的新方向盘无效,因为我未设置name属性。没什么,Rails从数据库中删除了我现有的方向盘记录!我了解并依靠构建关联在建立新记录时删除现有记录,但在新记录无效时不会删除。
有人知道如何解决这个问题吗?我已经尝试在事务中回滚,独立创建方向盘记录,并且仅在有效时才执行car.steering_wheel =方向盘。
答案 0 :(得分:0)
ActiveRecord默认情况下不对关联记录进行验证。
您必须使用validates_associated
:
class Car < ApplicationRecord
has_one :steering_wheel
validates_associated :steering_wheel
end
irb(main):004:0> Car.create!(steering_wheel: SteeringWheel.new)
(0.3ms) BEGIN
(0.2ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Steering wheel is invalid
from (irb):4
另外,如果您在steering_wheels.car_id
上设置了适当的外键,则数据库将不允许您执行car.build_steering_wheel
,因为它会孤立一个记录:
class CreateSteeringWheels < ActiveRecord::Migration[5.2]
def change
create_table :steering_wheels do |t|
t.belongs_to :car, foreign_key: true
t.string :name
t.timestamps
end
end
end
irb(main):005:0> c = Car.create!(steering_wheel: SteeringWheel.new(name: 'foo'))
(0.3ms) BEGIN
Car Create (0.7ms) INSERT INTO "cars" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2018-11-08 18:53:11.107519"], ["updated_at", "2018-11-08 18:53:11.107519"]]
SteeringWheel Create (2.4ms) INSERT INTO "steering_wheels" ("car_id", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["car_id", 3], ["name", "foo"], ["created_at", "2018-11-08 18:53:11.110355"], ["updated_at", "2018-11-08 18:53:11.110355"]]
(1.3ms) COMMIT
=> #<Car id: 3, created_at: "2018-11-08 18:53:11", updated_at: "2018-11-08 18:53:11">
irb(main):006:0> c.build_steering_wheel
(0.3ms) BEGIN
(0.6ms) ROLLBACK
ActiveRecord::RecordNotSaved: Failed to remove the existing associated steering_wheel. The record failed to save after its foreign key was set to nil.
from (irb):6
irb(main):007:0>
答案 1 :(得分:0)
这是has_one关联的build_associated方法的规定功能。 build_associated将删除现有的关联,无论正在构建的新关联是否有效。因此,如果在事务期间有任何您希望旧关联得以保留的情况,请不要使用build_associated。