简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM