如何在Rails 5 API中呈现文件?

yea*_*yer 8 ruby ruby-on-rails url-routing single-page-application

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

的routes.rb

match '*all', to: 'application#index', via: [:get]
Run Code Online (Sandbox Code Playgroud)

application_controller.rb

class ApplicationController < ActionController::API
  def index
    render file: 'public/index.html'
  end
end
Run Code Online (Sandbox Code Playgroud)

问题是这在API模式下不起作用.这只是一个空洞的回应.如果我将父类更改为ActionController::Base一切按预期工作.但我不想继承全班的膨胀,我需要纤薄的API版本.

我尝试过添加模块ActionController::Renderers::All,AbstractController::Rendering无论是否成功.

Ser*_*sev 13

如果我将父类更改为ActionController :: Base,则一切都按预期工作.但我不想继承全班的膨胀,我需要纤薄的API版本.

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

class StaticPagesController < ActionController::Base
  def index
    render file: 'public/index.html'
  end
end
Run Code Online (Sandbox Code Playgroud)

这样,你只有一个"臃肿"的控制器,而其他人仍然保持苗条和快速.