this happens particularly when try , update model.
i have quiz app, , add quiz using form:
<%= form_for(@quiz) |f| %> <% if @quiz.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@quiz.errors.count, "error") %> prohibited quiz being saved:</h2> <ul> <% @quiz.errors.full_messages.each |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class = 'field'> <%= f.label :difficulty, "difficulty of quiz, 1 3 3 being difficult" %> <%= f.text_field :difficulty %> </div> <div class="field"> <%= f.label :for_unsubscribed, "check have quiz visible logged in unsubscribed users" %> <%= f.check_box :for_unsubscribed %> </div> <%= f.fields_for :questions |question_attribute| %> <div class = 'inner-c'> <p> <%= question_attribute.label :content, "question" %> <span><b><%= question_attribute.index + 1 %></b></span> <br/> <%= question_attribute.text_area :content, :cols => 100, :rows => 4 %> </p> <p> <%= question_attribute.label :explanation, "answer explanation" %> <br/> <%= question_attribute.text_area :explanation, :cols => 100, :rows => 6 %> </p> <%= question_attribute.label :_destroy, "remove question"%> <%= question_attribute.check_box :_destroy %><br/> <%= question_attribute.label :passage, "reference passage" %> <br/> <%= question_attribute.text_area :passage, :rows => 3, :class => 'passage-input' %> <%#= question_attribute.label :question_explanation, "question explanation" %> <%#= question_attribute.text_area :question_explanation, :rows => 10 %> </p> <%= question_attribute.fields_for :answers |answer_attribute| %> <p> <%= answer_attribute.label :content, "answer" %> <%= answer_attribute.text_field :content %> <%= answer_attribute.label :correct_answer, "check indicate correct answer", :class => 'inline' %> <%= answer_attribute.check_box :correct_answer, :class => 'inline'%> </p> <% end %> </div> <!-- inner-c --> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %>
a new form generated controller so:
def new @quiz = quiz.new 50.times question = @quiz.questions.build 5.times { question.answers.build } end end
taking advantage of using nested models, quiz has_many
questions has_many
answers.
the problem -- when create quiz (with 50 questions), try , update quiz afterwards, fix mistake example, questions move out of order. question 43 , question 1 might switch places. absolutely need questions stay in same order after update them can't figure out how make happen. ideas?
generally in rdbms order not specified default, unless explicitly state it. therefore if don't specify order can results in order an expected behaviour.
but according description question 43 swapped question 1 after update, can think ordering them updated_at
timestamp. try order explicitly order questions id
– id
[normally] primarykey , never changes, questions stay in order.
Comments
Post a Comment