Skip to content

Commit

Permalink
Fix #dup with custom serialisation
Browse files Browse the repository at this point in the history
While `write_uploader` is aliased to `write_attribute` by default,
it may be overridden in the model. This change ensures that the
override method is called when clearing the attribute.
  • Loading branch information
nassim-platogo committed Jan 7, 2025
1 parent f062091 commit 7cda4e4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/carrierwave/orm/activerecord.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def initialize_dup(other)
super
@_mounters[:"#{column}"] = nil
# The attribute needs to be cleared to prevent it from picked up as identifier
write_attribute(_mounter(:#{column}).serialization_column, nil)
write_uploader(_mounter(:#{column}).serialization_column, nil)
_mounter(:"#{column}").cache(old_uploaders)
end
Expand Down
24 changes: 24 additions & 0 deletions spec/orm/activerecord_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2181,6 +2181,30 @@ def initialize_dup(*)
end
end

context 'when #write_uploader is overridden in the model' do
before do
Event.class_eval do
attribute :called_write_uploader_with, :json, default: {}
def write_uploader(*args)
self.called_write_uploader_with[args] ||= 0
self.called_write_uploader_with[args] += 1
write_attribute(*args)
end
end
@event = Event.new
end

it "clears previous attribute value to prevent unintended deduplication" do
@event.image = stub_file('test.jpeg')
@event.save
new_event = @event.dup
new_event.save

expect(new_event.called_write_uploader_with[[:image, nil].to_s]).to eq 1
expect(new_event.image.url).to eq '/uploads/test.jpeg'
end
end

context ':mount_on in options' do
before { Event.mount_uploader(:image_v2, @uploader, mount_on: :image) }
it do
Expand Down

0 comments on commit 7cda4e4

Please sign in to comment.