storage service 名は DB に保存されている
storage service を変更すると以下のようなエラーが表示される。
KeyError in ActiveStorage::Blobs::RedirectController#show
config.active_storage.service
service名を変更するとDBとの整合性が取れなくなる
production.rb
config.active_storage.service = :product
production.rb
config.active_storage.service = :user
原因は保存時に service 名がDBに保存されているから
原因としては、画像を保存する際に Rails が自動的にDBにどの storage に保存したのかを書き込んでくれているからだ。
product.rb
class Product < ApplicationRecord
has_one_attached :main_img
has_many_attached :sub_imgs
end
実際に保存されているデータ
active_storage_blobs
というテーブルに保存されている
解決方法
SQLでデータを更新する
update blobs
UPDATE active_storage_blobs SET service_name = 'user' WHERE service_name = 'product';
migrationを発行して修正する
create migrate
rails generate migration UpdateActiveStorageServiceName
def change
ActiveStorage::Blob.where(service_name: 'product').update_all(service_name: 'user')
end