2016-11-12 49 views
1

我運行這個耙:耙子中止了! ::的ActionView ::模板錯誤:未定義的方法「挑戰」的零:NilClass

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 

現在也許在each方法本身有沒有辦法不發送用戶的誰不」沒有任何挑戰?

我不斷收到此錯誤:

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

用戶has_many挑戰和挑戰belongs_to用戶。

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 %> 
+0

錯誤表示您沒有任何'用戶',對nil:NilClass'有'未定義方法'挑戰',意味着用戶是nill。確保你的數據庫包含用戶。 – Sravan

+0

所以,你可以試試'如果user && user.challenges.present? && user.challenges.any?' – Sravan

+0

請把你的看法和郵件也這樣能夠檢查這個問題提出 – Sunny

回答

2

請更新您的耙子任務

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 

我認爲,如果你的用戶量提升錯誤不在第n條記錄中有任何電子郵件請嘗試此操作

+1

讓我們使用User.find_each!如果你有這麼多的用戶,User.all風險很大。順便說一句,月度報告只是會發送一些條件,更好的方法是User.where(某些),性能會提高很多! –

+0

好的我會更新這個 – Sunny

相關問題