Rails 3 - how to send_file in response of a remote form in rails?

Mr_Nizzle picture Mr_Nizzle · May 16, 2011 · Viewed 10.8k times · Source

I have this coupon form

    <%form_for(:download,:download,:url=>{:controller=>"coupons",:action=>"verifycoupon"},:remote=>true) do |f| %>
    <%=text_field :download,:code%>
    <%=f.submit "verify"%>
    <%end%>

and after validating the code on the controller's action i have a confirmation like:

render :update do |page|
    page.alert "OK"
end

Now I want to send a file to the browser with the send_file instruction but nothing seems to happen

send_file("/path/to/my/file.extension")

and in the log I can see

"Sent file /path/to/my/file.extension (0.1ms)"

I was wondering if there's something like

render :update do |page|
   page.send_file("/path/to/my/file.extension")
end

 

#### Update #######

my Controller's action looks something like

def verifycoupon
   code = Code.find(params[:download][:code])
   if code
     if code.is_active?
     render :update do |page|
        page.alert "ok"
     end
       send_file("/path/to/my/file.extension")
     else
       render :update do |page|
          page.alert "this code has already been used"
       end
     end
   else
   render :update do |page|
     page.alert "Code does't exist"
   end
   end
end

Answer

OfficeYA Virtual Offices picture OfficeYA Virtual Offices · Oct 30, 2012

I have the same problem, well kind of.

In my view I had a link_to tag with remote: true.

The link aimed an action that produced a PDF. The PDF was generated (with prawn and thinreports) and sent, but the download dialog did not popup.

So I remove the remote: true and add a target: '_self', so it ended up like this (I am using haml)

!= link_to image_tag( 'print.png' ) + (I18n.t :buttons)[:comments][:print],
    customer_comment_path(@address_book),
    { target: '_self' }

And it worked just fine.

I did not have to do the "Ajax Request -> Server -> Response -> Redirect -> Client -> request which downloads -> ..." mentioned above.