Ruby on Rails send_file, code in controller action

2019-02-20 22:53发布

问题:

I'm running into a weird issue with user downloadable files, the file is downloading properly, but other code in the controller action is executing twice. I'm using CarrierWave, which is mounted on a Document model at .file.

I want users to be able to click this link to download the file:

<%= link_to document.file.file.filename, document_path(document)  %>

This is what my controller looks like:

  def show
    document = Document.find(params[:id])

    # Track this download
    CourseDownload.create(course: document.course, user: current_user)   

    # Download the file
    send_file 'public' + document.file.url.to_s
  end

When I click the link, the file downloads, but 2 CourseDownload records are created. In the logs it looks like the GET request is happening twice:

Started GET "/documents/1" for 127.0.0.1 at 2014-04-17 18:12:47 -0400
Processing by DocumentsController#show as HTML
  Parameters: {"id"=>"1"}
  Document Load (0.2ms)  SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1  [["id", "1"]]
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'xxx' LIMIT 1
  CACHE (0.0ms)  SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1  [["id", "1"]]
public/uploads/document/file/1/bootstrap-3.0.0.zip
Sent file public/uploads/document/file/1/bootstrap-3.0.0.zip (0.1ms)
Completed 200 OK in 7ms (ActiveRecord: 0.4ms)


Started GET "/documents/1" for 127.0.0.1 at 2014-04-17 18:12:47 -0400
Processing by DocumentsController#show as HTML
  Parameters: {"id"=>"1"}
  Document Load (0.2ms)  SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1  [["id", "1"]]
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'xxx' LIMIT 1
  CACHE (0.0ms)  SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1  [["id", "1"]]
public/uploads/document/file/1/bootstrap-3.0.0.zip
Sent file public/uploads/document/file/1/bootstrap-3.0.0.zip (0.1ms)
Completed 200 OK in 5ms (ActiveRecord: 0.3ms)

Any idea what I'm doing wrong?

Thanks!

回答1:

The issue ended up being caused by a turbolinks gotcha.

Resolved with:

<%= link_to document.file.file.filename, document_path(document), 'data-no-turbolink' => true %>