Search code examples
ruby-on-railsactionmailermailer

NilClass error setting up mailer


I'm trying to set up a mailer for the first time. I've followed the RubyGuides Mailer Basics to the letter, or so I thought. I keep getting a NilClass error. Originally, it was because my email address wasn't saving to the DB (left if off of the controller). Now I'm able to see my email address in the rails console, but still running into NilClass or an "wrong number of arguments 0 for 1" error

Here's my controller:

def create
@pc = Pc.new(pc_params)

respond_to do |format|
  if @pc.save
    TestMailer.message(@pc).deliver_later

    format.html { redirect_to @pc, notice: 'Pc was successfully created.' }
    format.json { render :show, status: :created, location: @pc }
  else
    format.html { render :new }
    format.json { render json: @pc.errors, status: :unprocessable_entity }
      end
    end
  end

My mailer:

   class TestMailer < ApplicationMailer
      default from: '[email protected]'

      def message(pc)
        @pc = pc
        @url  = 'http://example.com/login'
        mail(to: @pc.email, subject: 'Welcome to My Awesome Site')
      end
    end

I don't get what I'm missing here, any help?


Solution

  • Retraced my steps after a short time away from the screen. Seems I might have failed to correctly name my email template. Started from scratch using Ruby Guides and got it working. New code for future lost souls:

    Controller:

    def create
    @pc = Pc.new(pc_params)
    
    respond_to do |format|
      if @pc.save
        PcsMailer.email(@pc).deliver_later
    
        format.html { redirect_to @pc, notice: 'Pc was successfully created.' }
        format.json { render :show, status: :created, location: @pc }
      else
        format.html { render :new }
        format.json { render json: @pc.errors, status: :unprocessable_entity }
      end
    end
    

    Mailer:

    class PcsMailer < ApplicationMailer
      default from: '[email protected]'
    
      def email(pc)
        @pc = pc
        @url  = 'http://example.com/login'
        mail(to: @pc.email, subject: 'Welcome to My Awesome Site')
      end
    end
    

    Message:

       <!DOCTYPE html>
        <html>
          <head>
         <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
          </head>
          <body>
            <h1>Welcome to example.com </h1>
          </body>
        </html>
    

    Mostly copied directly from Ruby Guides, though some things were eliminated for simplicity.