title: ordering a has_many collection for validation before saving to database
body: <p>My models need to enforce a particular ordering of a has_many association at all times even before new rows get added to the database.</p>
  
  <p>Suppose I have a has_many/belongs_to association as follows:</p>
  
  <pre><code>    class Assembly &lt; ActiveRecord::Base
        has_many :parts, :order =&gt; "part_number ASC"
      end
  
      class Part &lt; ActiveRecord::Base
        belongs_to :assembly
      end
  </code></pre>
  
  <p>As I understand it, the <code>:order</code> flag on the <code>has_many</code> association will order the records coming out of the database by appending an <code>ORDER BY</code> clause to the SQL query. However, in my case, it is also important that the parts collection in Assembly be ordered for the validation to work and that has to happen even before the records get written to the database.</p>
  
  <p>I've experimented with this a little in the rails console by doing the following:</p>
  
  <pre><code>a = Assembly.new
  p1 = Part.new( :part_number =&gt; 2 )
  p2 = Part.new( :part_number =&gt; 1 )
  
  a &lt;&lt; p1    #p1 is added first but should be in second place in collection
  a &lt;&lt; p2    #p2 is added second but should be in first place in collection
  
  a.parts[0]    #expecting to see part_number=1 but I still get part_number=2
  </code></pre>
  
  <p>Consequently, the validate routine for the new assembly object would not work. Can somebody recommend the best way to enforce ordering of the has_many collection before writing to the database?</p>