我的 Rails 应用程序从 Rails 6 升级到 Rails 7 后遇到问题。当我尝试 render_to_string
模板时,我收到 ActionView::MissingTemplate 异常。
由于这工作正常,我不禁想到 Rails 7 有一些我找不到的新方法。
我的代码如下:
Controller
class SomethingController < ApplicationController
...
def my_action
html_string = render_to_string(template: 'something/template.html.erb', locals: {id: params[:id]})
end
end
我的期望(以及我过去的行为)是取回处理后的模板 View ,但我收到的是异常:
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
如果能提供我在这里遗漏的任何线索,我将不胜感激。
最佳答案
@user973254多亏了评论,帮助我解决了这个问题:
This answer might be helpful: rails render_to_string giving errors with partial view
事实证明,现在还需要通过 render_to_string
方法传递 formats:
参数。
我对代码的补充是:
- 添加
格式:
参数 - 删除
template:
参数的'html.erb'
部分 - 添加
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
关于ruby-on-rails - Rails 7 - render_to_string - MissingTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72479400/