Skip to content

Commit

Permalink
Make sure attributes are updated before calling callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
benedikt committed Jul 18, 2018
1 parent 11e289e commit 6387036
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/active_record_upsert/active_record/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def upsert!(attributes: nil, arel_condition: nil, validate: true)
raise ::ActiveRecord::ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
raise ::ActiveRecord::RecordSavedError, "Can't upsert a record that has already been saved" if persisted?
validate == false || perform_validations || raise_validation_error
values = run_callbacks(:save) {
run_callbacks(:save) {
run_callbacks(:create) {
attributes ||= changed
attributes = attributes +
Expand All @@ -15,8 +15,6 @@ def upsert!(attributes: nil, arel_condition: nil, validate: true)
}
}

@attributes = self.class.attributes_builder.build_from_database(values.first.to_h)

self
end

Expand All @@ -29,6 +27,7 @@ def upsert(*args)
def _upsert_record(upsert_attribute_names = changed, arel_condition = nil)
existing_attributes = attributes_with_values_for_create(self.attributes.keys)
values = self.class._upsert_record(existing_attributes, upsert_attribute_names, [arel_condition].compact)
@attributes = self.class.attributes_builder.build_from_database(values.first.to_h)
@new_record = false
values
end
Expand Down
10 changes: 10 additions & 0 deletions spec/active_record/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ module ActiveRecord
record.upsert
end

it 'updates the attribute before calling after callbacks' do
MyRecord.create(id: 'some_id', name: 'Some name')

allow(record).to receive(:after_s) { expect(record.name).to eq('Some name') }
allow(record).to receive(:after_c) { expect(record.name).to eq('Some name') }
allow(record).to receive(:after_com) { expect(record.name).to eq('Some name') }

record.upsert
end

context 'when the record does not exist' do
it 'sets timestamps' do
record.upsert
Expand Down

0 comments on commit 6387036

Please sign in to comment.