【问题标题】:Rails: Use of absolute path in Rails 6Rails:在 Rails 6 中使用绝对路径
【发布时间】:2019-12-11 14:02:24
【问题描述】:

最近,我将我正在维护的 Rails 应用程序升级到 Rails 6 RC2(来自 5.2.3)。因此,在升级之后,我立即运行了自动化测试 (RSpec),测试输出给了我很多弃用警告。其中一个警告是:

DEPRECATION WARNING: render file: should be given the absolute path to a file

于是我去了触发警告的视图文件,做了如下修改,

之前: render file: 'devise/sessions/new'

之后: render file: Rails.root.join('app', 'views', 'devise', 'sessions', 'new.html.slim')

我再次运行测试,没有看到弃用警告的输出。但是,切换到绝对路径后,视图现在只呈现纯 HTML 代码,但如果我删除 .slim 扩展名,即

render file: Rails.root.join('app', 'views', 'devise', 'sessions', 'new.html')

相应的视图已正确呈现,但现在测试会抱怨未使用绝对路径。有没有办法解决这个问题,或者这是 Rails/Slim 的错误?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    在您的情况下,您似乎想要呈现普通视图,即 模板

    在这种情况下,不推荐使用file 选项。相反,您应该使用 template 选项。

    render template: 'devise/sessions/new'
    

    或者更好的是,你可以使用这个快捷方式:

    render 'devise/sessions/new'
    

    背景

    file 选项旨在呈现在 Rails 应用程序外部的视图,您不能依赖 Rails 的视图查找逻辑。因此 Rails 想要有一个绝对路径。要求绝对路径也迫使开发人员考虑相对路径段 (/../)。

    省略.slim 扩展名,然后让模板引擎处理文件是模板的一项功能。使用file 似乎提供了完全相同的功能,但我猜这只是视图路径查找内部工作的副作用。看起来 Rails 开发人员希望在未来改善文件和模板之间的区分,而弃用相关文件是一个中间步骤,以免破坏太多依赖使用 file 并仍然期望模板功能的现有应用程序。

    PS:不需要手动分割路径。因此,如果您出于某种原因仍想将file 与绝对路径一起使用,而不是

    render file: Rails.root.join('app', 'views', 'devise', 'sessions', 'new.html.slim')
    

    使用这个

    render file: Rails.root.join('app/views/devise/sessions/new.html.slim')
    

    【讨论】:

    • 我将视图作为文件渲染为扩展布局。添加绝对路径不会消除弃用警告。
    【解决方案2】:

    在开发 Rails 6 仅限 API 的应用程序时,我遇到了同样的挑战。

    我想从一个名为 home_controller.rb 的控制器渲染一个静态页面

    这是我的代码

    require 'rails/application_controller'
    
    class HomeController < Rails::ApplicationController
      def index
        render file: Rails.root.join('public/index.html')
      end
    end
    

    但是当我尝试访问该页面时,我得到了错误:

    Started GET "/favicon.ico" for ::1 at 2021-02-23 16:25:41 +0100
    Processing by HomeController#index as */*
      Parameters: {"other"=>"favicon"}
    Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms | Allocations: 301)
     
    ArgumentError (`render file:` should be given the absolute path to a file. '/home/my-computer/Projects/MyWebsite/public/index.html' was given instead):
    

    我是这样解决的

    问题是我在public 目录中丢失了文件index.html,所以Rails 找不到它。

    我所要做的就是将文件index.html 添加到目录public 中。这次我测试的时候很好。

    就是这样。

    我希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2012-10-02
      • 2023-03-31
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多