如何在 Rails 5 API 中渲染文件? [英] How to render file in Rails 5 API?

查看:35
本文介绍了如何在 Rails 5 API 中渲染文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 React 编写的单页应用程序,带有 Ruby on Rails 后端(API 模式).Rails 还提供静态文件.我将 Rails 路由器指向 public/index.html,这样我的 SPA 就可以使用 react-router 管理他自己的路由.这是制作直接链接和刷新工作的常见做法.

I have a single-page application written in React with Ruby on Rails back-end (API mode). Rails is also serving static files. I'm pointing Rails router to public/index.html, so my SPA could manage his own routing with react-router. This is common practice in order to make direct links and refresh to work.

routes.rb

match '*all', to: 'application#index', via: [:get]

application_controller.rb

class ApplicationController < ActionController::API
  def index
    render file: 'public/index.html'
  end
end

问题是这在 API 模式下不起作用.这只是一个空洞的回应.如果我将父类更改为 ActionController::Base 一切都按预期工作.但是我不想继承full class的臃肿,我需要slim API version.

The problem is this doesn't work in API mode. It's just an empty response. If I change the parent class to ActionController::Base everything works as expected. But I don't want to inherit the bloat of full class, I need slim API version.

我尝试添加像 ActionController::Renderers::AllAbstractController::Rendering 这样的模块但没有成功.

I've tried adding modules like ActionController::Renderers::All and AbstractController::Rendering without success.

推荐答案

如果我将父类更改为 ActionController::Base,一切都会按预期进行.但是我不想继承full class的臃肿,我需要slim API version.

If I change the parent class to ActionController::Base everything works as expected. But I don't want to inherit the bloat of full class, I need slim API version.

是的,如果您从 ApplicationController 提供索引,更改其基类会影响所有其他控制器.这是不好的.但是如果你有一个专门的控制器来服务这个页面呢?

Yes, if you serve index from ApplicationController, changing its base class would affect all other controllers. This is not good. But what if you had a specialized controller to serve this page?

class StaticPagesController < ActionController::Base
  def index
    render file: 'public/index.html'
  end
end

这样,您只有一个臃肿"的控制器,而其他控制器保持纤薄和快速.

This way, you have only one "bloated" controller and the others remain slim and fast.

这篇关于如何在 Rails 5 API 中渲染文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆