“为什么我的Rails控制器中的'download_file'方法被调用了两次,尽管我只有一个'link_to'按钮触发它?我已经尝试禁用turbolinks和回调,但问题仍然存在,每次下载发生时都会删除两个credit。下面是我的'download_file'方法的相关代码和触发它的链接:
#dashboard_controller.rb
def download_file
puts "download_file method called"
if current_account.credit < 1
redirect_to root_path, notice: "You don't have enough credits to download this file."
else
puts current_account.credit
current_account.credit -= 1
current_account.save
file = File.open("#{Rails.root}/test_file.zip", "r")
self.response.headers["Content-Type"] = "application/zip"
self.response.headers["Content-Disposition"] = "attachment; filename='test_file.zip'"
self.response_body = file
end
end
#routes.rb
get 'download_file', to: 'dashboard#download_file', as: 'download_file'
#dashboard>show.html.erb
<%= link_to "Download", download_file_path, class: "download-button" %>
字符串
1条答案
按热度按时间yx2lnoni1#
我也面临着同样的问题,我花了一段时间才找到解决方案。在我这边,我面临的问题与涡轮链接有关。通过应用这里描述的解决方案(https://stackoverflow.com/a/14310416),它解决了这个问题。
在您的例子中,如果使用Rails 5,请尝试以这种方式更新link_to
字符串