※carrierwaveでアップロードはできている前提です。
carrierwaveの設定
developmentではapp/public/uploads
配下に保存して、
productionではGoogle Cloud Storageに保存します。
fuga_uploader.rb
class FugaUploader < CarrierWave::Uploader::Base
...
# Choose what kind of storage to use for this uploader:
if Rails.env.production?
storage :fog
else
storage :file
end
...
1. コントローラーに処理追加
app/controllers/hoge_controller.rb
def download
hoge = Hoge.find(download_params[:id])
image = hoge.image # imageはFugaUploaderオブジェクト
send_data(image.read, filename: "download#{File.extname(image.path)}")
end
...
def download_params
params.permit(:id)
end
2. viewにリンク設置
ターボリンク使っている場合は、turbolinks: "false"
しないとURLが変わっちゃいます。
app/views/hoge/show.html.erb
<div>
<%= link_to download_hoge_path(@hoge), data: { turbolinks: "false", confirm: 'ダウンロードしますか?' } do %>
<%= image_tag @hoge.image.to_s %>
<% end %>
</div>
3. ルーティング設定
config/routes.rb
resources :hoge do
member do
get :download
end
end