【问题标题】:How to render file in Rails 5 API?如何在 Rails 5 API 中渲染文件?
【发布时间】:2017-05-11 09:47:19
【问题描述】:

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

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,一切都会按预期工作。但是我不想继承完整类的臃肿,我需要苗条的 API 版本。

我尝试添加诸如 ActionController::Renderers::AllAbstractController::Rendering 之类的模块,但没有成功。

【问题讨论】:

  • 试试render_to_string file: 'public/index'
  • @Md.FarhanMemon 空响应
  • 添加扩展看看,.html
  • @Md.FarhanMemon 还是空的
  • 你试过render html: 'file_name'吗?

标签: ruby-on-rails ruby url-routing single-page-application


【解决方案1】:

如果我将父类更改为 ActionController::Base 一切都会按预期工作。但是我不想继承完整类的臃肿,我需要苗条的 API 版本。

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

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

这样,您只有一个“臃肿”的控制器,而其他控制器则保持纤细和快速。

【讨论】:

  • 这完全救了我的命,我整个周末都在和这个作斗争。非常感谢。
  • 和凯特一样,成功了!
【解决方案2】:

你可以这样做

render text: File.read(Rails.root.join('public', 'index.html')), layout: false

【讨论】:

  • 这会将文件的内容呈现为网页上的文本。还尝试了 html: 选项。
  • 对不起,我当时不明白这个问题,但现在你似乎有答案了:)
  • text 在 Rails 5 中已弃用。
  • @pj.martorell 我想现在是plain
【解决方案3】:

我通常只是将重定向_到“文件路径”。

def export
    # When the route coming to get 'some_report/export', to: 'greate_controller#export'
    # The file where you write or preparing, then you can redirect some path like : http://localhost:3000/public/tmpfile/report20210507.xlsx
    # And it will just redirect the file for you
    file_path = "public/tmpfile/report20210507.xlsx"
    redirect_to "#{root_url}#{file_path}"
end

对于这个例子

root_url = "http://localhost:3000/"

【讨论】:

    【解决方案4】:

    这应该可行,并允许您继续从 ActionController::API 继承--

    class ApplicationController < ActionController::API
      def index
        respond_to do |format|
          format.html { render body: Rails.root.join('public/index.html').read }
        end
      end
    end
    

    使用 Rails 5 更改了 ActionController::API 的渲染逻辑。

    【讨论】:

    • 它对#`不起作用undefined method respond_to'
    猜你喜欢
    • 2023-04-09
    • 2015-12-10
    • 2011-09-09
    • 2022-11-29
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多