title: Sort order for ActiveRecord::Associations::CollectionProxy in table rails
body: <p>I want to set up sort order for active record collection proxy in table.
  It should be sorted by number of available rooms (from highest to lowest).
  The trick is that <code>@rooms.reserved</code> is a boolean and to calculate quantity of free/reserved rooms I have to use helper method to avoid record collection proxy errors. I get proper results, but I need to sort table by number of available rooms. </p>
  
  <p>I have two models: Room and Hotel.</p>
  
  <pre><code>class Room &lt; ApplicationRecord
    belongs_to :hotel, optional: true # avoiding rails 5.2 belongs_to error 
    accepts_nested_attributes_for :hotel
  end
  </code></pre>
  
  <p>and</p>
  
  <pre><code>class Hotel &lt; ApplicationRecord
    has_many :rooms, dependent: :destroy
    accepts_nested_attributes_for :rooms
  end
  </code></pre>
  
  <p>I have table:</p>
  
  <pre><code>&lt;table&gt;
    &lt;tr&gt;
      &lt;th&gt;Name&lt;/th&gt;
      &lt;th&gt;Rooms count&lt;/th&gt;
      &lt;th&gt;Rooms status: in reserve || free&lt;/th&gt;    
    &lt;/tr&gt;
  
    &lt;% @hotels.each do |hotel| %&gt;
      &lt;tr&gt;
        &lt;td&gt;&lt;%= hotel.name %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= hotel.rooms_count %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= rooms_reservation_status(hotel.rooms) %&gt;&lt;/td&gt;  &lt;!-- rooms_reservation_status helper method in application_helper.rb --&gt;      
        &lt;td &gt;&lt;%= link_to 'Show', hotel_path(hotel) %&gt;&lt;/td&gt;
        &lt;td&gt;&lt;%= link_to 'Destroy', hotel, method: :delete, data: { confirm: 'Are you sure?' } %&gt;
      &lt;/tr&gt;
    &lt;% end %&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>Helper method</p>
  
  <pre><code># rooms_reservation_status iterates throught ActiveRecord::Associations::CollectionProxy 
  # and calculates the sum of free rooms aswell as a sum of reserved rooms
    def rooms_reservation_status(rooms)
      reserved = 0
      free     = 0
      rooms.each do |r|
        r.reserved == true ? reserved+=1 : free+=1
      end
      "#{reserved} || #{free}"
    end
  </code></pre>
  
  <p>Active Record table for rooms:</p>
  
  <pre><code>class CreateRooms &lt; ActiveRecord::Migration[5.1]
    def change
      create_table :rooms do |t|
        t.boolean :reserved, :default =&gt; false
        t.belongs_to :hotel, index: true
  
        t.timestamps
      end
    end
  end
  </code></pre>