LoginSignup
6
11

More than 3 years have passed since last update.

ActiveStorageで恒久的なURLを取得する

Last updated at Posted at 2019-12-16

この記事はFusic その2 Advent Calendar16日目の記事です。

経緯

弊社内にはTamelというQiitaに似た社内情報共有ツールがあります。
Railsのバージョンが古くなってもいたので、刷新プロジェクトを走らせているのですが、
特に苦労したのはファイルアップロード機能をPaperclipからActiveStorageに移行する作業でした。

ActiveStorageを使って困ったこと

いろんな記事を参照しながら、ActiveStorageを使うとurl_forメソッドでは、ワンタイムURLしか発行できないようです。
Tamelでは記事をMarkdownで書くため、ファイルのURLが記事のレコードに登録されます。
ワンタイムURLがレコードに登録されても、期限が切れたら画像が表示されないという問題がありました。

気づいたこと

ファイルを参照するだけの口をつくるだけでいいかー、とコントローラーを作り、pathが正しく登録されているか確認するために、以下のコマンドを叩いてみると、こんな記述が。

bundle exec rake routes
                   rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
            rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
                   rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
            update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
                 rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create

むむ、rails_blob_representationってなんだ?
と思って調べてみると、どうやら恒久的なURLを発行してくれるもののようでした。

対応方法

↓のようにrails_representation_urlというものを読んで上げれば良さそう。

class Medium < ApplicationRecord
  has_one_attached :file

  def url
    helpers = Rails.application.routes.url_helpers
    helpers.rails_representation_url(file.variant({}), only_path: true)
  end
end

こうすると、

Medium.first.url

みたいな形で恒久的なURLが取れます。

どう動いているのか

中身を読んでみると、このURLにアクセスすると、どうやら、ワンタイムURLへリダイレクトしてくれるようです。

まだ、深いところまでは追えていないのですが、また、何か分かったらこの記事に追記したいと思います。

まとめ

自分で実装する前に気づいてよかった。

6
11
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
6
11