Rails: send_data/send_file でデータの中身がテキストとして表示される問題

問題

次のようなRailsのアクションにより files/example.pdf の中身をユーザーにダウンロードさせたい。

class FilesController < ApplicationController
  def show
    filename = 'example.pdf'
    path = Rails.root.join('files', filename)
    send_file(path, type: 'application/pdf', filename: filename)
  end
end

しかし、ブラウザでこのアクションにアクセスするとファイルの中身がテキストとして表示される。

解決法

<a> タグに data-turbolinks="false" 属性を付ける。例えば、

<%= link_to "example.pdf", file_path %>

<%= link_to "example.pdf", file_path, 
  data: { turbolinks: false } %>

に変える。

参考資料