Search code examples
ruby-on-railssortingassociationsmodel-associationsactive-form

Is it possible to sort a "built" record in a rails form?


I've a few questions opened surrounding this topic and each time I try some approach I go down a different rabbit hole.

What I would like to know is if it is possible to sort an objects join attributes collection based on some value in the collection?

For example in my code's edit action I have

  def edit
    Size.all.each do |size|
      unless @cake.sizes.exists?(size.id)
        @cake.cake_details.build(size_id: size.id, price: nil)
      end
    end
    @cake_details_collection = @cake.cake_details.order(:size_id)
  end

I'd like to sort it because the built records get added last to the form and then it makes the form look inconsistent and confusing.

Also the reason I have it like above is that in the update action I remove any association when a checkbox is unchecked and text_field is left blank.

This is the section of my form related to above:

<div class="field">
  <%= form.fields_for :cake_details do |details| %>
      <%= details.check_box :size_id, {}, details.object.size_id %><br />
      <%= details.text_field :price %><br />
  <% end %>

Everything else so far is working for destroying the parent object and for creation. Am I nearly there or a million miles away?


Solution

  • Progress! So I didn't know I could sort the fields in the form below

    <div class="field">
      <%= form.fields_for :cake_details, @cake.cake_details.sort_by(&:size_id) do |details| %>
          <%= details.check_box :size_id, {}, details.object.size_id %><br />
          <%= details.text_field :price %><br />
      <% end %>