0
0

storage.yml の active_storage service を変更すると 500 エラーで画像が表示されなくなる問題

Posted at

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 というテーブルに保存されている

image.png

解決方法

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0