Rails 找不到模板

Template is not found by Rails

Rails 5.1

In my controllers/fw_exports_conttroller.rb, I have:

def import_spreadsheet
  @import_spreadsheet = FwExport.new
  render template: "fw_exports/_import_spreadsheet"
end

当我 select 此控制器操作的菜单项时,我收到以下错误消息:

Processing by FwExportsController#import_spreadsheet as HTML
ActionView::MissingTemplate (Missing template fw_exports/_import_spreadsheet with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :slim, :coffee, :jbuilder]}. Searched in:
  * "/home/utils/rails/follower_wonk/app/views"
  * "/home/utils/.rvm/gems/ruby-2.4.2/gems/devise_invitable-1.7.2/app/views"
  * "/home/utils/.rvm/gems/ruby-2.4.2/gems/devise-4.3.0/app/views"
):
FATAL -- : [d37603eb-3da3-4ad2-b81b-29198e6bb773] app/controllers/fw_exports_controller.rb:67:in `import_spreadsheet'

我确认

app/views/fw_exports/_import_spreadsheet.html.slim

确实存在。有任何想法吗?

或者,可能:

class FwExportsController < ApplicationController

  def import_spreadsheet
    @import_spreadsheet = FwExport.new 
  end

end

如果您有 app/views/fw_exports/import_spreadsheet.html.slim(一个视图,而不是局部视图),那么我认为它将由 default/convention 渲染。

通过“_” fw_exports/_import_spreadsheet.html.slim 看起来像一个部分,当渲染部分时你可以跳过 partial 选项并且只传递 views 文件夹之后的文件路径,在你的情况下:

def import_spreadsheet
  @import_spreadsheet = FwExport.new
  render 'fw_exports/import_spreadsheet'
end

注意 render 'fw_exports/import_spreadsheet' 即使文件没有“_”前缀也能正常工作,这与 template 选项不同,后者不接受部分文件。

Layout documentation and from this post 看来你不应该在你的部分中添加下划线。

文档指出:

Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the :template option (which was required on Rails 2.2 and earlier)

这意味着您不需要提供控制器的路径,因为您在这里处理的是同一控制器:

根据@SebastiánPalma 建议编辑

def import_spreadsheet
  @import_spreadsheet = FwExport.new
  render "fw_exports/import_spreadsheet"
end

应该可以简单地解决您的问题。在 Rails V2.2 之前还需要 template 但由于您使用的是 5.1,因此不需要使用它。你可以简单地做 render 'import_spreadsheet'

我假设您需要渲染 Template 而不是 Partial

要渲染 Template,您需要将 _import_spreadsheet.html.slim 重命名为 import_spreadsheet.html.slim

您需要在代码中进行以下修改

步骤1

def import_spreadsheet
  @import_spreadsheet = FwExport.new
  render template: "fw_exports/import_spreadsheet"
end

此处您需要从 _import_spreadsheet

中删除 _

步骤 2

将文件重命名为 app/views/fw_exports/import_spreadsheet.html.slim 而不是 app/views/fw_exports/_import_spreadsheet.html.slim

如果您刚刚更新到 Rails 5.1 并看到此错误,也可能是由于在控制器中使用 render nothing 引起的,因为此方法已在 Rails 5.1 中删除。这并不总是很明显,因为有时控制器行可能在堆栈跟踪中有几层深。但是,如果您检查堆栈跟踪中所有控制器的行号并发现 render nothing,您就找到了罪魁祸首。如果这确实是您的问题,您需要做的就是更换这个旧方法。

例如,如果您的旧代码是: render nothing: true, status: 403

您可以通过将其更改为以下内容来修复错误:head :forbidden