Reputation: 305
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!
Upvotes: 0
Views: 41
Reputation: 599
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.
Upvotes: 1