NoMethodError,nil的未定义方法:NilClass

时间:2013-04-30 10:38:07

标签: ruby-on-rails activerecord ruby-on-rails-3.2

我有一个带有rails的测验应用

当用户获得测验然后检查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之前执行?

如果@ a.first.timer&lt; 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>

1 个答案:

答案 0 :(得分:3)

问题在于您不应检查查询结果的可为空性。

尝试替换

if @check == nil

if @check.empty?