0

I'm working on a site that shows multiple-choice questions. Users have the ability to add new questions. I want to call the next question from a button, so I need that button to update the page with the next ActiveRecord item.

My Controller:

def practice
  shuffled_questions = Array.new(Question.ids).shuffle 
  @question = Question.find(shuffled_questions.pop)
end

My view shows one question at a time, and I don't want any questions to repeat, which is why I'm pulling them out of an array, but I don't know how to update @question with the next id in the array from the view.

My first thought was to update the page using AJAX or an OnClick function, but that didn't seem to work.

I've read through other people updating their models and controllers to get the next ActiveRecord item, and I see what they're doing, such as here, but that didn't help me understand how to call the update from the view.

Thanks so much for the help!

Martin
  • 295
  • 1
  • 2
  • 10
  • 1
    For every request, the controller action is executed again and the `shuffled_questions` array is recreated. Thus, `@question` is not persisted across requests (not even across AJAX requests). – Tamer Shlash Jan 12 '18 at 23:08

1 Answers1

1

In this particular line:

shuffled_questions = Array.new(Question.ids).shuffle

you're creating a new array and shuffling it each time you fire the practice action as @Tamer Shlash pointed out.

You could try this:

def practice
  @shuffled_questions = Array.new(Question.ids).shuffle if @shuffled_questions.empty?
  @question = Question.find(@shuffled_questions.pop)
end

Now, when you call the practice action, it will only create a new array and shuffles it if @shuffled_questions is empty otherwise it will persist the shuffled questions array, and you can get the next questions as you intend.

amrrbakry
  • 589
  • 7
  • 17
  • Amr, you were very close, but not quite right, though you lead me to the right answer. The code I needed was actually `@shuffled_questions = Array.new(Question.ids).shuffle if @shuffled_questions.count == 0` because when `@shuffled_questions = []` its actually not a nil value, its an empty array. – Martin Jan 13 '18 at 22:33