Sometimes can be useful to send a file to the user instead of rendering a page. When you have a fixed location for the file you simply achieve this with a link to the file inside the view, but there may be some cases in wich you have to dinamically generate the file to send. To do this you have to add a new custom action to the controller wich you want to add the download to. In this example let’s suppose to have a simple blog application where the user can download the content of a post in text format.
So, in the posts controller we add the following action:
1 2 3 4 5 6 7 8
After this we have to add a new line into our
config/routes.rb file to make this action accessible with a get request:
1 2 3 4 5
Now we can add a simple link in our view:
Here we suppose to have the instance variable
@post created somewhere (i.e. in the show action). Now we can display our page and download the post as a text file.
Hope this helps, have fun with Ruby on Rails!