I got a task to generate some reports in excel format. Generating file wasn’t any problem and I’ve finished it in few minutes. Next step was serving this generated files from the controller.
Easy part: Serving files from controller
I have generated reports in .xlsx. I’ve created a model for keeping filename and creation date. I wanted to serve them from rails controller to ensure, that user has access to that file. I’ve written this simple controller part. Fetching file name from the database, opening the file with `File.open`. I’m using `send_file` method as return value from action. I’m setting type to `application/xlsx` and disposition to `attachment` browser knows, that it should download a file in xlsx format.
def show work_report = WorkReport.find(params['id']) file = File.open('work_reports/' + work_report.file_name) send_file file, type: 'application/xlsx', disposition: 'attachment' end
I was linking to files with the link_to helper. I’ve set type and disposition attachment. What possibly could go wrong?
<%= link_to(work_report.file_name, work_report_path(export)) %>
Problem: linking to action properly
I was pretty sure that it’s going to work. Instead, I got the binary representation of file despite setting disposition and type. It was totally weird for me and I was pretty nervous about it. It’s something stupid and I have problem like that. I was desperate and started googling the problem.
After some looking for answer, I learnt that I should specify target to `_self` in my link. I’ve set my target in link_to and then magic, it works!
<%= link_to(work_report.file_name, work_report_path(export), target: '_self') %>
Why? I still have no idea. As far as I know `_self` is the default value for a target, so it shouldn’t be changing anything, but it does. If you know something about that issue, I’d be glad to hear an explanation of this.
If you like it, you can follow me on twitter/facebook or subscribe to push notifications(red mark in the left down corner of the page).