1

我有一个带有导轨的测验应用程序,

当用户得到一个测验然后检查 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'

你可以在控制器上看起来像

第 29 行在检查 quizuser 后读取,如果为nil quizuser.create

为什么timer之前执行@check

如果@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>
4

1 回答 1

3

问题是您不应该检查查询结果的可空性。

尝试更换

if @check == nil

if @check.empty?
于 2013-04-30T10:48:50.690 回答