Skip to content

Commit

Permalink
Merge pull request #138 from wata727/destroy_with_operated_at
Browse files Browse the repository at this point in the history
Allow passing operated_at to destroy
  • Loading branch information
wata727 authored Jul 18, 2023
2 parents 54c3345 + fb88120 commit 7c7216f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
9 changes: 4 additions & 5 deletions lib/activerecord-bitemporal/bitemporal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -334,22 +334,21 @@ def _update_row(attribute_names, attempted_action = 'update')
end || false
end

def destroy(force_delete: false)
def destroy(force_delete: false, operated_at: Time.current)
return super() if force_delete

current_time = Time.current
target_datetime = valid_datetime || current_time
target_datetime = valid_datetime || operated_at

duplicated_instance = self.class.find_at_time(target_datetime, self.id).dup

ActiveRecord::Base.transaction(requires_new: true, joinable: false) do
@destroyed = false
_run_destroy_callbacks {
@destroyed = update_transaction_to(current_time)
@destroyed = update_transaction_to(operated_at)

# 削除時の状態を履歴レコードとして保存する
duplicated_instance.valid_to = target_datetime
duplicated_instance.transaction_from = current_time
duplicated_instance.transaction_from = operated_at
duplicated_instance.save_without_bitemporal_callbacks!(validate: false)
if @destroyed
@_swapped_id_previously_was = swapped_id
Expand Down
2 changes: 1 addition & 1 deletion lib/activerecord-bitemporal/callbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ module Callbacks
define_model_callbacks :bitemporal_destroy
end

def destroy
def destroy(...)
perform_bitemporal_callbacks? ? run_callbacks(:bitemporal_destroy) { super } : super
end

Expand Down
8 changes: 8 additions & 0 deletions spec/activerecord-bitemporal/bitemporal_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,14 @@ class EmployeeWithUniquness < Employee
it { expect { subject }.to change(employee, :transaction_from).from(updated_time).to(destroyed_time) }
it { expect { subject }.not_to change(employee, :transaction_to) }
end

context "with operated_at" do
subject { employee.destroy(operated_at: destroyed_time) }
it { expect { subject }.not_to change(employee, :valid_from) }
it { expect { subject }.to change(employee, :valid_to).from(ActiveRecord::Bitemporal::DEFAULT_VALID_TO).to(destroyed_time) }
it { expect { subject }.to change(employee, :transaction_from).from(updated_time).to(destroyed_time) }
it { expect { subject }.not_to change(employee, :transaction_to) }
end
end

describe "#touch" do
Expand Down

0 comments on commit 7c7216f

Please sign in to comment.