MyFirstRails

ActiveStorageでのZIPファイルアップロード

概要

Railsにこれから初めて触れる方を対象にしたチュートリアルです 本チュートリアルでは、ActiveStorageを使用したZipファイルのアップロードサイトを作成します

チュートリアル

Railsのひな型を作る

まず、rails newを実行し、Railsアプリのひな型を作成します

rails new zip

次に、作成したRailsアプリのディレクトリへと移動します

cd zip

SQLite3のバージョン修正

先ほどのrails newsqlite3のインストールがエラーになっている場合は、以下のようにバージョンを指定してください

gem 'sqlite3', '1.3.13'

その後、bundle installを実行します

bundle install

ActiveStorageのインストール

早速、ActiveStorageをインストールします インストール方法は非常に簡単で、以下のコマンドを実行するだけです

rails active_storage:install

新しいマイグレーションファイルが生成されるので、rails db:migrateを実行します

rails db:migrate

次に、Zipファイルを取り扱うModelを作成します 特にカラムなどは指定しなくてもOKです

rails g model zipfile

再び、rails db:migrateを実行します

作成したZipfileモデルにhas_one_attached :fileを追加します

class Zipfile < ApplicationRecord
    has_one_attached :file
end

次に、rails g controller web indexを実行してアップロードするフォームを作成します

rails g controller web index

コマンド実行後、config/routes.rbapp/views/web/index.html.erbを以下のように修正します

Rails.application.routes.draw do
  root 'web#index'
  get 'web/index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
class WebController < ApplicationController
  def index
    @zipfile = Zipfile.new
  end
end
<h1>Web#index</h1>
<p>Find me in app/views/web/index.html.erb</p>

<%= form_with model: @zipfile, local: true do |form| %>
    <%= form.file_field :file %><br>
    <%= form.submit %>
<% end %>

これでrails sでローカルサーバを建てた後、localhost:3000にアクセスするとフォームが表示されています

次に、app/controllers/zipfiles_controller.rbを作成します


class ZipfilesController < ApplicationController
    def create
        @zip = Zipfile.new(zipfile_params)
        @zip.save!
        redirect_to :root
    end

     private

         def zipfile_params
            params.require(:zipfile).permit(:file)
        end
end

その後、config/routes.rbを編集します

Rails.application.routes.draw do
  root 'web#index'
  get 'web/index'
  resources :zipfiles, :only => [:create]
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

これでlocalhost:3000からZIPファイルをアップロードできるようになりました! ちなみに、アップロードしたZIPファイルはstorageディレクトリ以下にアップロードされています

ダウンロードもできるようにする

ZIPファイルをアップロードするだけでは面白くありません せっかくアップロードしたので、ダウンロードもできるようにしたいと思います

まず、config/routes.rb/zipifilesへのルーティングを追加します 追加で、root_pathを変更します

Rails.application.routes.draw do
  root 'zipfiles#index'
  get 'web/index'
  resources :zipfiles, :only => [:index, :create]
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

次に、app/controllers/zipfiles_controller.rbindexアクションを追加します

class ZipfilesController < ApplicationController

    def index
        @zipfiles = Zipfile.all
    end

    def create
        @zip = Zipfile.new(zipfile_params)
        @zip.save!
        redirect_to :root
    end

    private

        def zipfile_params
            params.require(:zipfile).permit(:file)
        end
end

最後に、app/views/zipfiles/index.html.erbを作成します

<p id="notice"><%= notice %></p>

<h1>Zipfiles</h1>

<table>
  <thead>
    <tr>
      <th>Link</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @zipfiles.each do |zipfile| %>
      <tr>
        <td><%= link_to 'Download', rails_blob_path(zipfile.file, disposition: "attachment") %></td>
      </tr>
    <% end %>
  </tbody>
</table>

実装の肝となっているのはlink_toヘルパーメソッドに渡しているrails_blob_pathです rails_blob_pathActiveStorageへのパスを表示できるようにしています そのファイルパスをlink_toへと渡すことでダウンロードができるようになっています

これで、ZIPファイルをダウンロードできるようになりました!

ライセンス

MITライセンス