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>