为什么我的模型属性会出现故障?

时间:2016-09-02 04:02:15

标签: ruby-on-rails

当我尝试更新模型时,这种情况经常发生。

我有一个测验应用,我使用此表单添加测验:

<%= 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 %>

控制器会生成一个新表单,如下所示:

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

利用嵌套模型,其中has_many回答问题的has_many问题。

问题是 - 当我创建一个测验(有50个问题)时,我会尝试更新测验,然后修复一个错误,例如,问题不按顺序移动。问题43和问题1可能会切换位置。在我更新它们之后,我绝对需要问题保持相同的顺序,但我无法弄清楚如何实现这一点。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

通常在默认情况下不指定RDBMS顺序,除非您明确说明它。因此,如果您没有指定订单,您可以按任何顺序获得结果,这是预期的行为。

但根据你的描述,问题43在更新后与问题1交换,所以我认为你是按updated_at时间戳排序的。尝试按id明确订购问题 - id [通常]是一个PrimaryKey,它永远不会改变,因此您的问题将保持有序。