Search code examples
ruby-on-railsruby-on-rails-5applicationcontroller

Using "ApplicationController.new.render_to_string" in a Rails api app (config.api_only = true)


I have a Rails 5 app build as an api app:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.api_only = true
  end
end

In one of my controller actions I need to render some Ruby flavoured html, and then serve it back in the json response.

A standard Rails app do this:

# app/controllers/my_controller.rb
def my_action
  html = ApplicationController.new.render_to_string("my_erb_or_haml_file", locals: {foo: "bar"}, layout: false)
  render :json => {html: html}, :status => :ok
end

However, for my slimmed api app ApplicationController.new.render_to_string seems to just render " ". This confuses me, because I would expect it to either serve the content or raise an exception.

Any suggestions what route I should take in order to generate Ruby flavoured html?


Solution

  • I guess you have to explicitly use base class. Your application is an API app, so your controller is probably inheriting from ActionController::API

    ActionController::Base.new.render_to_string