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: ->(*) { 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