Rails Form form_for Objects Reverse Order of Array

This is pretty simple, but I couldn’t figure out how to do it.  Basically I had a view that went through each object in the nested table array, and rendered it.  However, instead of rendering them all in the order they were created from top to bottom on the page, I wanted to render them in reverse order, so the most recent one was at the top of the page.  There might be several ways of doing this, but here is how I finally did it, and its pretty simple. (probably shouldn’t have taken me this long to figure it out, but hopefully you can read this and save some time!)

Here is the original code in the view:

<%= simple_form_for(@lot) do |f| %>
  <strong>Lot Number:</strong> <%= @lot.number %>
  <strong>Item</strong> <%= Item.find(@lot.item_id).number_rev_name %>
  <strong>Inventory Quantity:</strong> <%= @lot.inventory_qty %>

  <-- Here is where I render a partial for each build_lot, which is a 
         has_many, :through join_table -->
  <%= f.simple_fields_for :build_lots,  do |build_lot| %>
    <%= render 'build_lot_fields', :f => build_lot %>
  <% end %>
  <%= f.button :submit, class: 'btn btn-primary' %>
<% end %>

And here is the code from the partial for each build_lot, _build_lot_fields.html.erb

<div class='nested-fields build-lot-fields'>
  <div class='well'>
    <%= f.input :my_build_id, collection: MyBuild.order(:start_date), label_method: :description, value_method: :id, :prompt => 'Choose a Build', selected: MyBuild.where(current: true), input_html: { id: 'build_select'} %>
    <%= f.input :pull_quantity, label: 'Pull Quantity', as: :string %>
    <%= f.label 'Date' %><%= Date.today %><br>
    <%= f.input :employee_id, collection: Employee.order(:first_name), label_method: :first_name, value_method: :id, prompt: "Choose your name" %>

So this simple trick to reverse the order of the build_lots array that is iterated through to render each partial, is to simply add another parameter to the fields_for call (in this case simple_fields_for from the simple_form gem). This second parameter that we add will be the build_lots array reversed. You can find more about the usage of the fields_for method on its documentation page.

But first we need to create this reversed array in the controller. So in the controller (in the function for the view where I want to show the reversed build_lots) I added this line:

@reverseBuildLots = @lot.build_lots.reverse

Then back in the view, I simply change the form_for line like this:

<%= f.simple_fields_for :build_lots, @reverseBuildLots do |build_lot| %>

passing in the @reverseBuildLots parameter, which is an array of build_lots in reverse order that we created in the controller.

Pretty simple, but took me a while to figure out. Hopefully this will save you some time!

credit here