I'm trying to make a simple link that when clicked initiates the download of a document associated with a particular resource. I have a Resource model and in that model there is a column called "document". I am able to successfully view the document inline when the link is clicked, but I would prefer to download it. I have been reading about content-types and send_file, but I haven't been able to completely piece this together to function.
Here is the code that I think I need to use for the link:
<%= link_to 'Download File', :action => "download_file" %>
This throws an error:
ActiveRecord::RecordNotFound in ResourcesController#show
Couldn't find Resource with id=download_file
When I change the link to this, it opens the file in the browser:
<%= link_to 'Open file', resource.document_url, :target => "_blank" %>
In my ResourcesController I have this method defined:
def download_file
@resource = Resource.find(params[:id])
send_file(@resource.file.path,
:filename => @resource.file.name,
:type => @resource.file.content_type,
:disposition => 'attachment',
:url_based_filename => true)
end
I have a route set up in routes.rb like this:
resources :resources do
get 'resources', :on => :collection
end
So based upon this error, it would seem that my download_file method in ResourcesController is not able to determine the id of the resource record that the document is associated with.
I'm running: Rails 3.2.11 Carrierwave 0.8.0 Ruby 1.9.3-p194
I would appreciate some insight into this. I have searched a number of articles and was not able to find a simple tutorial. Thanks.