I'm building a very simple single-page Rails app with a single form using the remote: true
option. Basically, the use selects a few options on the form, and I render a set of products matching these requirements back to the page using the create.js.erb
view. So far, so good.
I'd also like to give the user the option to download a CSV list of the products. The problem is, with the remote: true
option, I can't figure out how to actually trigger the download. I can use the hack here to route to the correct format and action:
<%= button_tag( 'Download CSV', :value => 'csv', :name => 'format' ) %>
def create
respond_to do |format|
format.js
format.csv { send_data @products.to_csv }
end
end
This almost works; the correct CSV (text) data is returned in the browser response when I click the "Download CSV" button -- but it doesn't get rendered or trigger a file download, presumably because it's being returned in an AJAX response.
I could make this work by using a link, rather than submitting the form (assuming the action responds to 'GET'):
<%= link_to 'Download CSV', products_path(format: :csv) %>
But then I don't have access to the user data about the product requirements captured in the form parameters.
Is there any way to make this work, or do I need to lose the remote: true
and submit the form via HTML (non-AJAX) to trigger the CSV download?