Rogerio Nascimento
Rogerio Nascimento

Reputation: 339

Rails 7 - render_to_string - MissingTemplate

I'm facing an issue with my Rails app after upgrading it from Rails 6 to 7. When I try to render_to_string a template, I'm receiving ActionView::MissingTemplate exception.

As this was working fine, I can't help but to think there's some new approach to Rails 7, which I wasn't able to find.

My code below:

Controller

class SomethingController < ApplicationController

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

My expectation (and the behavior I used to have) was getting back the processed template view, but what I'm receiving back is the exception:

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'

Additional details:

I would really appreciate any clue to what I'm missing here.

Upvotes: 8

Views: 3775

Answers (2)

Emiliano Della Casa
Emiliano Della Casa

Reputation: 906

If you are using an "uncommon" format (such as :kml or :kmz or :xls) remember to add it in config/initializers/mime_type.rb otherwise the render function may not recognize it.

I had the same problem after a Rails 7 upgrade and that was the solution

Upvotes: 3

Rogerio Nascimento
Rogerio Nascimento

Reputation: 339

@user973254 helped me get this issue fixed, thanks to the comment:

This answer might be helpful: rails render_to_string giving errors with partial view

It turns out that it's now needed to pass also the formats: parameter with the render_to_string method.

My addition to the code, that got it working, was:

  1. Adding the formats: parameter
  2. Removing the 'html.erb' portion of the template: parameter
  3. Adding layout: false (which I haven't honestly tested to check if its that pivotal for this issue

Below I show the code that works.

class SomethingController < ApplicationController

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

Upvotes: 11

Related Questions