3

I have a form_for in a template new.html.erb where I do the normal save to the DB and then an e-mail on success. I want the mailer to send the same new.html.erb as the body and pass the model so that the form is fully populated. I'm getting the following error:

undefined method `protect_against_forgery?' for #<#<Class:0x000000049d7110>:0x000000049d4690>

On the line immediately after the form_for tag (since it's injecting the auth token tag I think). Is there a way I can circumvent this so that I can re-use the template in the mailer?

Here's what the mailer code looks like

class MaintenanceMailer < ActionMailer::Base
  helper :application  

  def request_email(maintenance)
    mail :to => maintenance.community.email, :subject => "Maintenance" do |format|
      format.html { render :layout => 'default', :template => 'maintenance/new' }
    end    
  end
end  
jpfuentes2
  • 2,085
  • 1
  • 18
  • 19

4 Answers4

6

Add this to a helper that only your mailer template uses:

    def protect_against_forgery?
      false
    end

But make sure that the receiving controller skips the verify_authenticity_token, and that session jacking is ok for whatever that form carries.

Sam Coles
  • 4,003
  • 24
  • 19
  • I tried that earlier and it gives me another error: ActionController::InvalidAuthenticityToken I want that action to verify authenticity on a normal page request for the form. Do I need to send something to the controller once I'm in the mailer? All it should have to do is now render that "new" template w/o going back to the controller. – jpfuentes2 Jul 29 '10 at 16:24
  • Yes, that's the skips "verify_authenticity_token" part. The syntax to do that in your controller (at the top) is: skip_before_filter :verify_authenticity_token, :only => [:my_form_action] – Sam Coles Jul 30 '10 at 07:31
4

I used the method Sam C suggested, but slightly adjusted it. Just before calling the render to string, I override the method.

ApplicationHelper.send(:define_method, :protect_against_forgery?) { false }
html = render_to_string(template: "quotations/show", layout: "application_print")

This overrides the protect_against_forgery? method temporarily.

Hendrik
  • 4,849
  • 7
  • 46
  • 51
0

I had the same problem working in a house sales page. Are you using form_for in your email template? Because this was my trouble, I built it using div's instead form_for and all worked fine.

0

you can just turn off the authenticity of the form_for in the template.new.html to avoid such errors

you can check this for How do i remove the authenticity_token from rails forms

Community
  • 1
  • 1
didi
  • 1
  • 2
  • I understand you are not eligible to post a comment yet. When posting links in / as an answer, try summarizing on the main idea that the link might elaborate on. – Nikhil Girraj May 17 '17 at 05:15