I’m working on my first application and I need some help with allowing my users to download a text file with certain variables that are being displayed on the page.
Take a shopping list for example.
Let’s say you allow your users to create a shopping list of products, and then display the shopping list with the items on a shopping list page,
e.g. localhost:3000/list/my-list
Take a look at the example code below (which is probably incorrect):
File.open('shopping_list.txt', 'w') do |file|
file.puts 'Item 1: #{product_1.name}'
file.puts 'Item 2: #{product_2.name}'
file.puts 'Item 3: #{product_3.name}'
end
Which then creates a text file that has the following content:
Item 1: Eggs
Item 2: Butter
Item 3: Bread
Users should then be able to download this file (i don’t want this file to be stored on the server) via a download link.
I have no idea how to achieve this, but I’m hoping you guys can guide me. 😀
TL;DR
- create text files populated with model data (perhaps create a method to achieve this?)
- text files should not be stored on the server, but created as users click the download button (not sure if this is the rails way but perhaps someone could show me a better way)
I am assuming there is a resource for
Listwith the attributenameas the name of the list and a listhas_manyItem which has an attributedescriptionFirst off, create a download path change your routes
config/routes.rbNow if you run a
rake routesin the console you should see a route likeWhats more you should now have the helpers
download_list_url&download_list_pathto use in your view likeIn your
lists_controlleradd the action, and as you dont actually want to keep the file on the server disk just stream the data as a stringFinally you see I have used a
as_filemethod which you should add to the model (I prefer not to do this stuff in controllers, fat models, skinny controllers). So in theListmodel