GeekToL
GeekToL

Reputation: 1815

NoMethodError, undefined method for nil:NilClass

I have a quiz app with rails,

When user get a quiz and then check quizuser if it is still empty, if empty then create quizuser, if not empty will continue.

Model

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

Here's error message

NoMethodError in QuizzesController#start

undefined method `timer' for nil:NilClass

app/controllers/quizzes_controller.rb:29:in `start'

You can looks like on controller

line 29 read after check quizuser, if nil quizuser.create

why timer execute before @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>

Upvotes: 1

Views: 8761

Answers (1)

Lazarus Lazaridis
Lazarus Lazaridis

Reputation: 6029

The problem is that you shouldn't check for nullability of a query result.

Try replacing

if @check == nil

with

if @check.empty?

Upvotes: 3

Related Questions