Introduction
In this blog post, we will dive into an issue that many developers face when working with Rails 6 and Active Storage. The error message “Could not find or build blob: expected attachable, got nil” can be quite perplexing, but fear not! We will explore the cause of this error and provide a solution to help you overcome it. So, let’s get started!
The Problem
When using Rails 6 and Active Storage, you might encounter an issue when trying to add images to an active_storage blob instead of replacing them. Despite following the documentation and using the attach
method, you may find that the default behavior of replacing all the images persists.
This problem typically arises when you have a form generated with Rails scaffold, and you want to allow multiple image uploads. You have set up the necessary associations and form fields, but the error message “Could not find or build blob: expected attachable, got nil” keeps appearing.
Investigation and Solution
To investigate this issue, let’s examine the code and identify the cause. In the update
action of your controller, you are using the attach
method to add the images to your @page
object. However, this is where the problem lies.
Rails 6 introduced a change in the default behavior of has_many_attached
associations. Previously, files were appended to the attachment list, but now they are replaced by default. To override this behavior and allow adding new images instead of replacing them, you can make a simple configuration change.
In your application.rb
file, add the following line:
code
config.active_storage.replace_on_assign_to_many = false
By setting replace_on_assign_to_many
to false
, you change the default behavior to append images instead of replacing them.
Once you have made this configuration change, you can remove the @page.images.attach(params[:images] )
line from your controller’s update
action. Rails will now handle the appending of images automatically, based on the form data.
Conclusion
In this blog post, we explored the issue of “Could not find or build blob: expected attachable, got nil” in Rails 6 Active Storage. By understanding the changes in Rails 6’s default behavior for has_many_attached
associations and making a simple configuration change, you can overcome this issue and allow the addition of images without replacing them.
We hope this article has provided clarity and a solution to this perplexing problem. If you have any further questions or insights, please feel free to leave a comment below.