我運行這個耙:耙子中止了! ::的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 %>
<% 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 %>
<% 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 %>
錯誤表示您沒有任何'用戶',對nil:NilClass'有'未定義方法'挑戰',意味着用戶是nill。確保你的數據庫包含用戶。 – Sravan
所以,你可以試試'如果user && user.challenges.present? && user.challenges.any?' – Sravan
請把你的看法和郵件也這樣能夠檢查這個問題提出 – Sunny