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

蹲街弑〆低调 提交于 2019-12-11 06:28:28

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51082180/using-applicationcontroller-new-render-to-string-in-a-rails-api-app-config-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!