Can't call destroy_all for ActiveRecord if validates_associated is defined for relation in Rails model

35 Views Asked by At

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?

1

There are 1 best solutions below

1
Oleksandr Bratashov On

Fixed this issue by adding validation:

class Device < ApplicationRecord
  # Now it supports only one device per car
  validates :car_id, uniqueness: { allow_nil: true,
                                   message: I18n.t('devices.messages.one_device_per_car') }

and migration

class AddUniqIndexCarIdToDevices < ActiveRecord::Migration[7.0]
  def change
    safety_assured do
      add_index :devices, :car_id, unique: true
    end
  end