From 1e258ae9a34f14ae2e7868cfb6ef6991e8d69c5c Mon Sep 17 00:00:00 2001 From: Nathan Stitt Date: Fri, 5 Feb 2021 10:41:50 -0600 Subject: [PATCH 1/2] only attach images that are not already present --- lib/has_attachments.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/has_attachments.rb b/lib/has_attachments.rb index b561b8bc..8b92ec38 100644 --- a/lib/has_attachments.rb +++ b/lib/has_attachments.rb @@ -25,7 +25,9 @@ def has_attachments(options={}) writeable: true, setter: ->(req) { req[:doc]['images'].each do |img| - self.images.attach(img['signed_id']) + unless self.images.detect{|i| i.signed_id == img['signed_id'] } + self.images.attach(img['signed_id']) + end end }, getter: ->(*) { From c159baf041c544c54425b3c679fad75bc38528b1 Mon Sep 17 00:00:00 2001 From: Nathan Stitt Date: Fri, 5 Feb 2021 10:58:12 -0600 Subject: [PATCH 2/2] add spec --- .../api/v1/exercises/representer_spec.rb | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/spec/representers/api/v1/exercises/representer_spec.rb b/spec/representers/api/v1/exercises/representer_spec.rb index f8617e18..9a201b31 100644 --- a/spec/representers/api/v1/exercises/representer_spec.rb +++ b/spec/representers/api/v1/exercises/representer_spec.rb @@ -89,8 +89,10 @@ module Api::V1::Exercises end context 'images' do - it 'are included' do + before(:each) do exercise.images.attach(io: File.open(Rails.root.join('public', 'favicon.ico')), filename: 'favicon.ico', content_type: 'image/jpeg') + end + it 'are included' do expect(representation).to( including( 'images' => [a_hash_including( @@ -107,6 +109,20 @@ module Api::V1::Exercises ) end + it 'only attaches when not already attached' do + expect { + # attempt to attach an image that is already attached + representer = described_class.new(exercise) + expect { + representer.from_hash('images' => [ + { 'signed_id' => exercise.images[0].signed_id }, + { 'signed_id' => exercise.images[0].signed_id }, + ] + ) + exercise.save + }.not_to change { exercise.images.count } + end + end context 'questions' do