簡體   English   中英

在Rails api應用中使用“ ApplicationController.new.render_to_string”(config.api_only = true)

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

我有一個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?

我猜你必須顯式地使用基類。 您的應用程序是一個API應用程序,因此您的控制器可能是繼承自ActionController :: API

ActionController::Base.new.render_to_string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM