rubysherpas / paranoia

acts_as_paranoid for Rails 5, 6 and 7
Other
2.89k stars 529 forks source link

belongs_to having with_deleted scope fails to decrement counter_cache #536

Open AndyGauge opened 1 year ago

AndyGauge commented 1 year ago

Given this example

capacity.rb

class Capacity

has_many :reservations
acts_as_paranoid
# includes integer attribute max in db schema

reservation.rb

class Reservation
belongs_to :capacity, -> { with_deleted }, counter_cache: true
acts_as_paranoid

Capacity represents something that can be reserved more than 1 time and reservation marks capacity as used. When a reservation is canceled (soft deleted) the counter cache does not decrement. Removing the -> { with_deleted } is a workaround.

Expectation

capacity = Capacity.create(max: 5)
2.times { capacity.create_reservation }
capacity.reservations_count = 2
capacity.reservations.count = 2
capacity.reservations.last.destroy
capacity.reservations_count = 1
capacity.reservations.count = 1

Actual Result

capacity = Capacity.create(max: 5)
2.times { capacity.create_reservation }
capacity.reservations_count = 2
capacity.reservations.count = 2
capacity.reservations.last.destroy
capacity.reservations_count = 2
capacity.reservations.count = 1

When a capacity is destroyed, reservations are also destroyed and we need to inform the user on these deleted items. Currently adding a second belongs_to relationship for the with_deleted scope so delegations remain functional.

mathieujobin commented 1 year ago

Oh interesting, I never used counter_cache definitely looks useful.

are you able to write a test and a patch for this? I will definitely review and include in a future release.

Thanks