user2422869
user2422869

Reputation: 760

Rails. How to download data via send_data?

I need to download binary data. I've tryed send_data method but it saves whole .html page. I cannot access send_data method out of controllers so I declared helper_method in app controller.

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :save_data

  def save_data
    send_data('Hello, pretty world :(', :type => 'text/plain', :disposition => 'attachment', :filename => 'hello.txt')
  end

end

What I do wrong? Thank you.

Upvotes: 0

Views: 4631

Answers (2)

Idan Arye
Idan Arye

Reputation: 12603

There is a reason send_data is only usable from a controller - it's because it doesn't make sense to use it from anywhere else. send_data is performed instead of rendering a view, so if you call it from a view, by the time Ruby reaches the command it already started writing the rendered view into the response, and that's why you get the full HTML page.

You need to make it a controller method. Once you have a route for it, you can use the helper for that route to put a link to that controller method in your view - not the file data itself.

Upvotes: 2

spickermann
spickermann

Reputation: 106822

You must call send_data instead of rendering a view. Making this a helper method and calling it from a view does not make any sense at all.

In short: You must have a controller method that send_data and has no view:

class TextController < ApplicationController
  def hello
    send_data('Hello, pretty world :(', 
              :type => 'text/plain', :disposition => 'attachment', :filename => 'hello.txt')
  end 
end

In your view you just have a normal link to that text#hello route.

Upvotes: 1

Related Questions