Emjay Emjay - 1 month ago 11
Ruby Question

bundle exec rake fails when pulling user attribute into mailer view

I can't get

bundle exec rake
or
rspec spec
to pass even though all individual tests pass and the mailer that the error references works correctly (e.g. it successfully sends the email with all attributes). This is causing my Travis build to fail. The error is:

/app/views/team_mailer/new_team.html.erb:8:in `_app_views_team_mailer_new_team_html_erb__3000815885147353905_70129791802460': undefined method `first_name' for nil:NilClass (ActionView::Template::Error)


/app/models/team.rb

class Team < ApplicationRecord
belongs_to :user
has_many :picks, dependent: :destroy
validates :name, presence: true

after_create :send_new_team_email

private
def send_new_team_email
TeamMailer.new_team(self).deliver_now
end
end


/app/controllers/teams_controller.rb

class TeamsController < ApplicationController
before_action :authorize_user_for_delete, only: [:destroy]
before_action :authorize_user_for_edit, only: [:edit]

def index
@user_teams = Team.where(user_id: current_user)
end

def new
@team = Team.new
end

def create
@team = current_user.teams.build(team_params)

if @team.save
flash[:notice] = "Team successfully created."
redirect_to @team
else
flash.now[:alert] = "Error creating team. Please try again."
render :new
end
end

private
def team_params
params.require(:team).permit(:name)
end


/app/mailers/team_mailer.rb

class TeamMailer < ApplicationMailer
default from: "Support@coolsite.com"

def new_team(team)
headers["Message-ID"] = "<#{team.user_id} team/#{team.id}@Pcoolsite.com>"
headers["In-Reply-To"] = "<#{team.user_id} team/#{team.id}@coolsite.com>"
headers["References"] = "<#{team.user_id} team/#{team.id}@coolsite.com>"

@team = team

mail(to: 'me@gmail.com', subject: "New team created")
end
end


/app/views/team_mailer/new_team.html.erb

<!DOCTYPE html>
<html>
<head>
<meta content = "text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>

<body>
<%= "#{@team.user.first_name} #{@team.user.last_name} created #{@team.name}" %>
</body>
</html>

Answer Source

I resolved this by validating class is not nil in /app/views/team_mailer/new_team.html.erb.

I also realized it was overkill to pass user. So, I eliminated the passing of it between models, controllers and views and just used @team.user.first_name and @team.user.last_name.

So the full line in /new_team.html.erb now reads:

<%= "#{@team.user.first_name} #{@team.user.last_name} created #{@team.name}" if @team.user %>

I updated the original posting to show the streamlined (removed user) approach.