How to Render File in Rails 5 API

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'
end
end

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

Render a view in Rails 5 API

You don't need to uncomment config.api_only = true for this purpose, just inherit your controller from ActionController::Base, or do it in your ApplicationController (default for common rails generation).

Code:

  1. For this controller only YourController < ActionController::Base
  2. For all apllication ApplicationController < ActionController::Base

Rails 5 api only app with home page

I was in the same boat, trying to do a Rails 5 API app that could still bootstrap from a single html page (taken over by JS on load). Stealing a hint from rails source, I created the following controller (note that it's using Rails' instead of my ApplicationController for this lone non-api controller)

require 'rails/application_controller'

class StaticController < Rails::ApplicationController
def index
render file: Rails.root.join('public', 'index.html')
end
end

and put the corresponding static file (plain .html, not .html.erb) in the public folder. I also added

get '*other', to: 'static#index'

at the end of routes.rb (after all my api routes) to enable preservation of client-side routing for reloads, deep links, etc.

Without setting root in routes.rb, Rails will serve directly from public on calls to / and will hit the static controller on non-api routes otherwise. Depending on your use-case, adding public/index.html (without root in routes.rb) might be enough, or you can achieve a similar thing without the odd StaticController by using

get '*other', to: redirect('/')

instead, if you don't care about path preservation.

I'd love to know if anyone else has better suggestions though.

Rendering multiple images from Ruby on Rails 5 API application

You could send a JSON response with your images base64-encoded as strings in an array. Or an object. Whatever is more appropriate for your app/code.



Related Topics



Leave a reply



Submit