如何获取模型属性以便按顺序保存?

时间:2016-09-03 02:35:59

标签: ruby-on-rails

我正在构建一个测验应用程序,以创建一个测验我这样做:

 def new
    @quiz = Quiz.new
    50.times do
    question = @quiz.questions.build
    5.times { question.answers.build }
  end
  end
enter code here

使用嵌套参数。问题是,有时测验不按顺序保存(例如当我创建新测验或更新现有测验时)。如果我按特定顺序创建测验,请问问题1,问题2,问题3,我希望在更新或创建测验后,该测验中的问题保持相同的顺序。现在,如果我更新测验,如果我想用quiz.questions.each do |question|

之类的东西显示测验,那么订单就会混乱

我不知道ruby数据库不强制执行命令,所以我如何确保如果我创建一个测验,我输入问题的顺序(从上到下)将始终是问题出现在?

如果您有兴趣,这是我用来创建测验的表格:

<%= form_for(@quiz) do |f| %>
  <% if @quiz.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@quiz.errors.count, "error") %> prohibited this quiz from being saved:</h2>

      <ul>
      <% @quiz.errors.full_messages.each do |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 to 3 with 3 being most difficult" %> 
    <%= f.text_field :difficulty %>

</div>
    <div class="field">
    <%= f.label :for_unsubscribed, "Check to have this quiz be visible to logged in but unsubscribed users" %>
    <%= f.check_box :for_unsubscribed %>


  </div>
    <%= f.fields_for :questions do |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 do |answer_attribute| %>
    <p>
      <%= answer_attribute.label :content, "Answer" %>
      <%= answer_attribute.text_field :content %>
      <%= answer_attribute.label :correct_answer, "Check to 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 %>

0 个答案:

没有答案