ActiveStorageにアップロードしたファイルのダウンロード
本日、ActiveStorageにアップロードしたファイルのダウンロード機能を実装しました。
ダウンロード機能を実装するのは初だったので結構手間取りましたw
その方法についてメモしておきます!!
①ActiveStorageの設定
以下のコマンドで、ActiveStorageに必要なデーブルやファイルを生成します。
rails active_storage:install
rails db:migrate
②モデルとの紐付け
taskモデルにfileを紐づけたかったので、task.rbに以下のように記述します。
これでfileとtaskが1対1で紐づくようになります。
task.rb
has_one_attached :file
③fileをアップロードできるようにする
viewは以下のようにfile_fieldでファイルをアップロードする部分を作ります。
views/tasks/new.html.slim
form_with model: @task, url: tasks_path, local: true do |f|
div
= f.label :title
= f.text_field :title
div
= f.label :description
= f.text_area :description
div
= f.label :deadline
= f.date_field :deadline
div
= f.label :priority
= f.select :priority, Task.priorities.keys
div
= f.label "ラベル追加"
ul#task_lavels
div
= f.label "ファイルを添付"
= f.file_field :file
div
= f.submit class: 'btn light-blue accent-2 margin_top'
コントローラでは、fileの情報を保存できるように設定します。
app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_action :require_sign_in
before_action :set_task, only: [:edit, :update, :destroy, :download]
略
def create
@task = current_user.tasks.new(task_params)
lavel_list = params[:tags]
if file = params[:task][:file]
@task.file.attach(file)
end
@task.save
if !@task.new_record?
@task.save_lavels(lavel_list)
redirect_to tasks_path
flash[:notice] = 'TODOを新規作成しました!'
else
render :new
end
end
略
private
def task_params
params.require(:task).permit(:title, :description, :deadline, :status, :priority, :file)
end
④ダウンロード機能作成
ダウンロードアクションのルーティングを設定します。
config/routes.rb
get 'tasks/download/:id' => 'tasks#download'
コントローラにdownloadアクションを作成します。
app/controllers/tasks_controller.rb
def download
data = @task.file.download
send_data(data, type: 'image/png', filename: 'download.jpg')
end
これでアクティブストレージに保存したファイルのダウンロード機能が実装できました!!
このままですと保存先がローカルになっていますが、保存先をS3に変更したかったので、以下の記事を参考にさせていただきました!!