Oleksandr Bratashov
Oleksandr Bratashov

Reputation: 908

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

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?

Upvotes: 0

Views: 29

Answers (1)

Oleksandr Bratashov
Oleksandr Bratashov

Reputation: 908

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

Upvotes: 0

Related Questions