Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

render_to_string in mailer causes subsequent render to fail

#6623

I'm using render_to_string in a mailer, and this prevents the rendering of the actual mail from finding the template.

This seems to be caused by @lookup_context being initialized on the mailer by render_to_string, then reused when rendering the mail. And this breaks because the mail extension (*.text.erb) is not found by the lookup context.

Here's a minimal example:

class NoteMailer < ActionMailer::Base
  default :from => "from@example.com"

  def foo
    @notes = []
    render_to_string(:template => "notes/index.html.erb") # <-- Removing this line makes the test pass
    # self.instance_variable_set(:@lookup_context, nil) # <-- So does enabling this
    mail(:to => "example@example.com")
  end
end

I'm attaching a minimal project containing a functional test that demonstrates this.

Reported by Jacob Tjørnholm · March 25th, 2011 @ 02:31 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. bhu
    bhu
    • Tag changed from actioncontroller, actionmailer to actioncontroller, actionmailer, rendering

    think i got the same error

     def cancellation(contract, user)
        @contract = contract
        kit = PDFKit.new(render_to_string('pdf/cancellation', :layout => false))
        kit.stylesheets << 'private/stylesheets/cancellation.css'
        
        attachments['Cancellation.pdf'] = kit.to_pdf
    
        options = {}
        options[:to] = contract.email
        options[:from] = user.email
        options[:bcc] = user.email if Variable.send_employee_email_bcc
        options[:subject] = "Cancellation"
    
        mail options
      end
    

    it renders nothing except the attachment which breaks the mail completely if there is no body.

    the format block helps getting around this but i dont think that it's intended for this kind of situation

    mail options do |format|
      format.text
      format.html
    end
    

    with this block the default behavior is some kind of restored. you have to explicitly specify every format. per real default rails is auto detecting which formats are available.

    Sorry for not really having a solution, just a workaround :/

    April 6th, 2011 @ 04:31 PM