Home How to call the next ActiveRecord item from the View
Reply: 1

How to call the next ActiveRecord item from the View

Martin Published in 2018-01-12 21:47:00Z

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)

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!

Amr El Bakry
Amr El Bakry Reply to 2018-01-13 23:33:38Z

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)

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328497 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO