How to render file in Rails 5 API? How to render file in Rails 5 API? ruby ruby

How to render file in Rails 5 API?


If I change the parent class to ActionController::Base everything works as expected. But I don't want to inherit the bloat of full class, I need slim API version.

Yes, if you serve index from ApplicationController, changing its base class would affect all other controllers. This is not good. But what if you had a specialized controller to serve this page?

class StaticPagesController < ActionController::Base  def index    render file: 'public/index.html'  endend

This way, you have only one "bloated" controller and the others remain slim and fast.


You could do

render text: File.read(Rails.root.join('public', 'index.html')), layout: false


I usually just redirect_to 'file path'.

def export    # When the route coming to get 'some_report/export', to: 'greate_controller#export'    # The file where you write or preparing, then you can redirect some path like : http://localhost:3000/public/tmpfile/report20210507.xlsx    # And it will just redirect the file for you    file_path = "public/tmpfile/report20210507.xlsx"    redirect_to "#{root_url}#{file_path}"end

For this example

root_url = "http://localhost:3000/"