在 Rails 5 API 中渲染视图

Render a view in Rails 5 API

我通过 rails new <application-name> --api 使用 Rails 5 生成了一个仅 API 的 rails 应用程序。我已经决定要包含一个用于测试某些内容的视图,但在加载视图时遇到问题。

我创建了一个包含一些文本的 users/index.html.erb 文件,我的控制器现在只是 def index; end 但是当我点击 /users URL 时没有任何显示.我还尝试在 config/application.rb 中注释掉 # config.api_only = true 但这没有任何影响。关于如何进行的任何建议?

您不需要为此取消注释 config.api_only = true,只需从 ActionController::Base 继承您的控制器,或者在您的 ApplicationController 中执行此操作(普通 [=25= 的默认设置) ]代).

代码:

  1. 仅限此控制器YourController < ActionController::Base
  2. 所有应用ApplicationController < ActionController::Base

这是来自 ActionController::Metal 文档 https://apidock.com/rails/ActionController/Metal

它说:

ActionController::Metal by default provides no utilities for rendering >views, partials, or other responses aside from explicitly calling of >response_body=, content_type=, and status=. To add the render helpers >you’re used to having in a normal controller, you can do the following:

class HelloController < ActionController::Metal
 include AbstractController::Rendering
 include ActionView::Layouts
 append_view_path "#{Rails.root}/app/views"

  def index
   render "hello/index"
  end
end

所以我自己尝试了一下,仅通过添加两个模块来添加实际上在 ActionController::API

中使用时效果很好