I've defined two models and added the validation of presence one device per car (we need to keep has_many devices for future requirements):
class Device < ApplicationRecord
belongs_to :car, validate: true
validates_associated :vehicle, message: I18n.t('devices.messages.one_device_per_car')
...
class Car < ApplicationRecord
has_many :devices, dependent: :nullify
validates :devices, length: { maximum: 1,
too_long: I18n.t('devices.messages.one_device_per_car') }
I need a correct handling device validation.
When I call car.devices.exists? # => true
But when I try to remove all devices car.devices.destroy_all # => []
Only delete all works fine car.devices.delete_all # => [...]
So, is there a way to fix destroy_all method?
Fixed this issue by adding validation:
and migration