LoginSignup
3
1

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す31(ActiveStorage route prefix編)

Posted at

はじめに

Rails 6 に追加されそうな新機能を試す第31段。 今回は、 ActiveStorage route prefix 編です。
Rails 6 では、 ActiveStorage route のプレフィックスを指定できるようになりました。

Ruby 2.6.3, Rails 6.0.0.rc1 で確認しました。Rails 6.0.0.rc1 は gem install rails --prerelease でインストールできます。

$  rails --version
Rails 6.0.0.rc1

準備

今回は、 Rails6 のちょい足しな新機能を試す15(Active Storage編) を元にして修正していきます。
Rails プロジェクトを作るところからの手順はそちらを参照してください。

View を修正する

User の詳細画面にイメージファイルのダウンロードリンクをつけます。
また、ActiveStorage の routes が変わったことがわかるように URL の情報を画面に表示します。

app/views/users/show.html.erb
...
    <%= image_tag @user.avatar %>
    <p>
      <%= link_to 'download image', rails_blob_path(@user.avatar, disposition: 'attachment') %> 
      from <%= rails_blob_path(@user.avatar, disposition: 'attachment').sub(/\/blobs\/.*/, '/blobs/') %>
    </p>
...

rails server を実行してユーザー登録する

rails server を実行してユーザー登録して詳細画面を表示します。
ダウンロード先のURL が /rails/actvie_storage/blobs であることがわかります。
before.png

route_prefix を設定する

config/environments/development.rb を開いて、 routes_prefix を設定します。

config/environments/development.rb
  ...
  config.active_storage.routes_prefix = '/files'
end

rails server を再実行して詳細画面を再表示する

rails server を再度、実行して登録したユーザーの詳細画面を表示します。
ダウンロード先のURL が /files/blobs に変わったことがわかります。

after.png

試したソース

試したソースは以下にあります。
https://github.com/suketa/rails6_0_0rc1/tree/try031_active_storage_route_prefix

参考情報

3
1
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
3
1