1

我有一个 Rails 5 应用程序构建为api 应用程序

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

在我的一个控制器操作中,我需要渲染一些 Ruby 风格的 html,然后在 json 响应中返回它。

一个标准的 Rails 应用程序这样做:

# 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

但是,对于我精简的 api 应用程序ApplicationController.new.render_to_string似乎只是呈现" ". 这让我很困惑,因为我希望它要么提供内容,要么引发异常。

有什么建议我应该采取什么路线来生成 Ruby 风格的 html?

4

1 回答 1

6

我想你必须明确使用基类。您的应用程序是 API 应用程序,因此您的控制器可能继承自 ActionController::API

ActionController::Base.new.render_to_string
于 2018-07-03T00:59:26.473 回答