Reputation: 5343
Consider the following
# setup an array of the question ids so far
questions_array = []
questions_array.push(session[:questions_array])
# take a random question whom id is not included in the session[:questions_array]
@question = Question.offset(rand(Question.count)).where('id NOT IN (?)',questions_array).take
# push id to array and later on assign the new array to the session
questions_array.push(@question.id)
session[:questions_array] = questions_array
I have two questions database. One of the two gets returned the other one gives me the error
NoMethodError (undefined method 'id' for nil:NilClass):
this line gives the error questions_array.push(@question.id)
this does not happen everytime! and that is what's strange!
Upvotes: 0
Views: 36
Reputation: 118289
This is how, you can solve it though:
Question
.where.not(id: questions_array)
.order('random()')
.first
But if the questions table get say more than 10,000 records for example, it will be slow. Then you could write recursive procedure, which will pick a random record and check some condition. if condition matches, returns the record, or recursion will go on with some base condition to break in worst case.
Upvotes: 2
Reputation: 5343
My bad seems that the problem lies in the fact that i first get a random id and then check if that id is not in the array which is not what i wanted. So if the random id was included in the array it would give an error as there is none to take.
this is the new line of code.
@question = Question.where('id NOT IN (?)',questions_array).first
Upvotes: 0