Quick background: Want to send a pdf to the client for download, some of the pdf's are static, and some we generate with pdftk.
So I hacked this together after looking at this question:
Rails 3 - how to send_file in response of a remote form in rails?
HTML
<select id="download_policy_docs_select">
<%= options_for_select(@file_list) %>
</select>
<input id="download_policy_doc" type="submit" class="btn btn-info btn-180px" value="DOWNLOAD" />
Ajax
$('#download_policy_doc').click(function(){
var doc = $('#download_policy_docs_select').val();
var policy_name = $('h1 :first').html();
console.log("hello");
$.ajax({
type: "POST",
url: "/policies/ajax_get_policy_document.pdf",
timeout: 3000,
success: do_the_success,
data: {document : doc, policy_name : policy_name}
});
});
Policies Controller:
def policy_declaration(id)
policy = Policy.find(params[:id] || id)
return unless enforce_policy_access(policy)
file_path = PolicyPdf.generate_policy_declaration(policy)
send_file(file_path, :filename => "#{policy.name}_declaration.pdf", :disposition => 'Content', :type => 'application/pdf')
end
def ajax_get_policy_document
policy = Policy.find_by_name(params[:policy_name])
if params[:document] == 'proof_of_insurance'
redirect_to :action => 'policy_declaration'
elsif params[:document] == 'master_cert'
#redirect_to PolicyPdf.get_policy_pdf_filepath(policy)
elsif params[:document] == 'im_declaration'
redirect_to :action => 'policy_declaration'
elsif params[:document] == 'im_master_cert'
# redirect_to PolicyPdf.get_policy_pdf_filepath(policy)
elsif params[:document] == 'invoice'
redirect_to policy_invoice
elsif params[:document] == 'legacy_cert'
redirect_to :action => 'policy_declaration'
else
"it's broke!"
end
end
My understanding was that while ajax can't download a file, if I redirected to this other method policy_declaration
and let it send the file, with the correct :disposition
then I could in fact download a file, because it was being sent from the server - but not as the response to the ajax request.
So, my questions are:
- Where did my understanding go wrong?
- Can I fix my current code to work as desired?
- If I can't do the above what should I do?
Even if the answer is 'no you can't do this use a form' I would still like to know where my understanding went wrong.
Also in case anyone asks why I tried to do it this way. I'm not very good with the rails form_helpers
(which is what a lot of other questions said to do)... So if that's the answer, some help in that direction would be very appreciated.