Skip to content

Commit

Permalink
Merge pull request #311 from openstax/fix/dupe-attach
Browse files Browse the repository at this point in the history
only attach images that are not already present
  • Loading branch information
nathanstitt authored Feb 5, 2021
2 parents 07b07c3 + c159baf commit 44ca265
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/has_attachments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: ->(*) {
Expand Down
18 changes: 17 additions & 1 deletion spec/representers/api/v1/exercises/representer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down

0 comments on commit 44ca265

Please sign in to comment.