In my Rails app, I let users cycle through different questions. I pass the questions to my view as well as an array containing indexes for all questions via my controller:
def index
@questions = Question.unanswered
@question_array = Array.new
@questions.each_with_index do |question, index|
@question_array << index
end
end
Then in my view, I use javascript to let users cycle through questions when clicking on an icon:
<div class="questions homeSection">
<div class="titleContainer questionTitle">
<p class="updateTitle">Recent Questions <icon class="fa fa-refresh"></icon></p>
</div>
<div class="question">
<% question_index = @question_array.sample %>
<% question = @questions[question_index] %>
<div class="question_content"><%= question.description %></div>
<div class="question_byline">from <%= link_to question.step.project.title, project_steps_path(question.step.project, :step_id => question.step.id) %> </div>
</div>
</div>
<script type="text/javascript">
// pick a random question to display
function cycleQuestion(){
<% old_question_index = question_index %>
console.log("old_question_index: <%= old_question_index %>");
<% new_question_array = @question_array - [old_question_index] %>
console.log("new_question_array: <%=new_question_array%>");
<% question_index = new_question_array.sample %>
console.log("new question_index: <%=question_index%>");
<% question_description = @questions[question_index].description %>
console.log("new question: <%=question_description%>");
$('.question_content').hide().html('<%=question_description%>').fadeIn();
$('.question_byline').hide().html('from <%=link_to question.step.project.title, project_steps_path(question.step.project, :step_id => question.step.id) %>').fadeIn();
}
</script>
The issue I'm having is that the ruby variable "question_index" does not seem to be persisting so that the refresh works once but then doesn't work again. You can see this in my console output:
clicked refresh
old_question_index: 1
new_question_array: [0]
new question_index: 0
new question: How do I ask a question?
clicked refresh
old_question_index: 1
new_question_array: [0]
new question_index: 0
new question: How do I ask a question?
How can I update the ruby variable "question_index" every time cycleQuestion is called?