[英]NoMethodError, undefined method for nil:NilClass
我有一個帶導軌的測驗應用,
當用戶獲得測驗然后檢查quizuser是否仍為空時,如果為空,則創建quizuser,如果不為空將繼續。
模型
class Quizuser < ActiveRecord::Base
belongs_to :user
belongs_to :quiz
end
class Quiz < ActiveRecord::Base
has_many :quizusers, :dependent => :destroy
end
class User < ActiveRecord::Base
has_many :quizusers, :dependent => :destroy
end
這是錯誤消息
NoMethodError in QuizzesController#start
undefined method `timer' for nil:NilClass
app/controllers/quizzes_controller.rb:29:in `start'
你可以在控制器上看起來像
檢查quizuser后讀取第29行,如果是nil quizuser.create
為什么timer
在@check
之前執行?
if @ a.first.timer <DateTime.now
@mu = Mu.find(params[:id])
@now = DateTime.now
@end = @now + @mu.quiz.time.minutes
@check = Quizuser.where(:quiz_id => @mu.quiz.id, :user_id => current_user.id)
if @check == nil
@a = Quizuser.create(:quiz_id => @mu.quiz.id, :user_id => current_user.id, :start => @now, :timer => @end)
@havequiz = Havequiz.new
@havequiz.answerusers.build
else
@a = Quizuser.where(:quiz_id => @mu.quiz.id, :user_id => current_user.id)
if @a.first.timer < DateTime.now
@a.update_column(:grade, 0)
redirect_to home_subdomain_path, :notice => 'Sorry your quiz time is over.'
else
@havequiz = Havequiz.new
@havequiz.answerusers.build
end
end
<div class="countdown"></div>
<script type="text/javascript">$(document).ready(function() {
var date = new Date('<%= @a.first.timer %>');
$('.countdown').countdown({
until: date,
format: 'dHMS'
});
});</script>
問題是您不應檢查查詢結果的可空性。
嘗試更換
if @check == nil
同
if @check.empty?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.