Skip to content

Commit

Permalink
Active Storage: Blob creation shouldn't crash if no service selected
Browse files Browse the repository at this point in the history
#41653 noted an issue where if there's service configured (`config.active_storage.service` is commented out), Blob creation via direct upload crashes:

```
Started POST "/rails/active_storage/direct_uploads" for ::1 at 2021-03-09 13:02:57 -0800
Processing by ActiveStorage::DirectUploadsController#create as JSON
  Parameters: {"blob"=>{"filename"=>"banana.jpg", "content_type"=>"image/jpeg", "byte_size"=>577085, "checksum"=>"W/vo/JqBNmJHMCaL+PRlBQ=="}, "direct_upload"=>{"blob"=>{"filename"=>"banana.jpg", "content_type"=>"image/jpeg", "byte_size"=>577085, "checksum"=>"W/vo/JqBNmJHMCaL+PRlBQ=="}}}
Completed 500 Internal Server Error in 12ms (ActiveRecord: 3.3ms | Allocations: 5864)

NoMethodError (undefined method `name' for nil:NilClass):

activestorage (6.1.3) app/models/active_storage/blob.rb:52:in `block in <class:Blob>'
activesupport (6.1.3) lib/active_support/callbacks.rb:427:in `instance_exec'
```

This PR fixes that crash. Blob creation will still fail, but with a more informative error about a `service_name` being required.
  • Loading branch information
ghiculescu authored and georgeclaghorn committed Mar 12, 2021
1 parent 168ddaa commit bd33dda
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion activestorage/app/models/active_storage/blob.rb
Expand Up @@ -49,7 +49,7 @@ class ActiveStorage::Blob < ActiveStorage::Record
scope :unattached, -> { where.missing(:attachments) }

after_initialize do
self.service_name ||= self.class.service.name
self.service_name ||= self.class.service&.name
end

after_update_commit :update_service_metadata, if: :content_type_previously_changed?
Expand Down
8 changes: 8 additions & 0 deletions activestorage/test/models/blob_test.rb
Expand Up @@ -252,6 +252,14 @@ class ActiveStorage::BlobTest < ActiveSupport::TestCase
end
end

test "doesn't create a valid blob if service setting is nil" do
with_service(nil) do
assert_raises(ActiveRecord::RecordInvalid) do
create_blob(filename: "funky.jpg")
end
end
end

test "invalidates record when provided service_name is invalid" do
blob = create_blob(filename: "funky.jpg")
blob.update(service_name: :unknown)
Expand Down
2 changes: 1 addition & 1 deletion activestorage/test/test_helper.rb
Expand Up @@ -102,7 +102,7 @@ def fixture_file_upload(filename)

def with_service(service_name)
previous_service = ActiveStorage::Blob.service
ActiveStorage::Blob.service = ActiveStorage::Blob.services.fetch(service_name)
ActiveStorage::Blob.service = service_name ? ActiveStorage::Blob.services.fetch(service_name) : nil

yield
ensure
Expand Down

0 comments on commit bd33dda

Please sign in to comment.