AnthonyGalli.com AnthonyGalli.com - 27 days ago 6
Ruby Question

rake aborted! ActionView::Template::Error: undefined method 'challenges' for nil:NilClass

I run this rake:

task monthly_report: :environment do
User.all.each do |user|
if user.challenges.present? && user.challenges.any?
UserMailer.monthly_report(user).deliver_now
end
end
end


Now maybe in the
each
method itself is there a way to not send to user's who don't have any challenges?

I keep getting this error:


ActionView::Template::Error: undefined method 'challenges' for nil:NilClass
after I run in production
heroku run rake monthly_report


A user
has_many
challenges and challenges
belongs_to
user.

user_mailer.rb

def monthly_report(user)
@user = user if user.email.present?
mail to: user.email, subject: "Sorry! Please Ignore | Testing Email - Monthly Challenges Report"
end


monthly_report.html.erb

Accomplished: <%= @user.challenges.accomplished.count %> Ongoing: <%= @user.challenges.unaccomplished.count %>

<% if @user.challenges.accomplished.present? %>
<% @user.challenges.accomplished.order("deadline ASC").each do |challenge| %>
<% if challenge.date_started != nil %>
<%= link_to challenge_url(challenge) do %>
<%= challenge.name %> <%= challenge.committed_description %> for <%= challenge.days_challenged %> Days
<% end %>&nbsp;&nbsp;
<% if challenge.deadline.present? %>
<span style="display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; background-color: #446CB3; text-decoration: none;"><%= challenge.deadline.strftime("%b %d, %Y") %></span>
<% end %>
<% else %>
<%= link_to challenge_url(challenge) do %>
<%= challenge.name %>
<% end %>&nbsp;&nbsp;
<% if challenge.deadline.present? %>
<span style="display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; background-color: #446CB3; text-decoration: none;"><%= challenge.deadline.strftime("%b %d, %Y") %></span>
<% end %>
<% end %>
<% end %>
<% else %>
None.
<% end %>

Answer

Please update your rake task

task monthly_report: :environment do
  User.all.each do |user|
    if user.email.present? && user.challenges.present? && user.challenges.any?
      UserMailer.monthly_report(user).deliver_now  
    end
  end
end

I think error raising if your user dose not have any email in th record try this