Rails 7 - render_to_string - MissingTemplate

5

我在将Rails 6升级到7后,我的Rails应用程序出现了问题。当我尝试render_to_string一个模板时,我会收到ActionView :: MissingTemplate异常。

由于这之前一直正常工作,所以我不禁想到Rails 7有一些新的方法,但我无法找到。

下面是我的代码:

控制器

class SomethingController < ApplicationController

  ...
  def my_action
     html_string = render_to_string(template: 'something/template.html.erb', locals: {id: params[:id]})
  end
  
end

我的期望(以及我过去的行为)是获取经过处理的模板视图,但我得到的是异常:

ActionView::MissingTemplate (Missing template something/template.html.erb with {:locale=>[:"pt-BR", :pt], :formats=>[:pdf], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}.

Searched in:
  * "/Users/user/rails/rn_igreja/app/views"
  * "/Users/user/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/devise-i18n-1.10.2/app/views"
  * "/Users/user/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/devise-4.8.1/app/views"
  * "/Users/user/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/actiontext-7.0.1/app/views"
  * "/Users/user/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/actionmailbox-7.0.1/app/views"
):

app/controllers/something_controller.rb:16:in `block in my_action'
app/controllers/something_controller.rb:12:in `my_action'

附加细节:

  • Ruby 版本:3.1.0
  • Rails 版本:7.0.2

请告诉我我错过了什么,非常感谢。


1
这个答案可能会有帮助:https://dev59.com/VVrUa4cB1Zd3GeqPilBj - user973254
2个回答

5

@user973254帮我解决了这个问题,感谢他的评论:

这个答案可能有帮助:rails render_to_string给部分视图带来错误

结果发现,使用render_to_string方法时也需要传递formats:参数。

我添加到代码中使其正常工作的内容是:

  1. 添加formats:参数
  2. 删除template:参数中的'html.erb'部分
  3. 添加layout: false(老实说我没有测试过它是否对此问题至关重要)

下面展示的是正常工作的代码。

class SomethingController < ApplicationController

  ...
  def my_action
      html_string = render_to_string(
        template: 'something/template',
        formats: [:html],
        locals: { id: params[:id] },
        layout: false
      )
  end
  
end

1

如果您正在使用“不常见”的格式(例如:kml、kmz或xls),请记得将其添加到config/initializers/mime_type.rb中,否则渲染函数可能无法识别它。

我在进行Rails 7升级后遇到了同样的问题,这就是解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接