Maintain the order of an array in rails forms

2019-09-09 08:56发布

问题:

I have 3 models (Workout, WorkoutSet, WorkoutStep) with the following associations:

  • A Workout has many sets
  • A WorkoutSet has many WorkoutSep
  • And a WorkoutStep has an array of videos (called video_usage[])

Using simple_form and cocoon I made the forms to edit such associations but, at the deepest level (the array of videos of WorkoutStep) by the time I edit a Workout, the order seem not to be constant, being, instead, ordered by (guessing) the last time the attribute has been modified (in this case, modified is changing a property, such as selecting another video).

I want the array of videos to remain constant between edits.

This is how my form looks like:

_workout_sets_fields.html.haml

.nested-fields
  = f.simple_fields_for :main_video_usage do |mv|
    = render 'main_video_usage_fields', f: mv
  .steps{ :style => "margin-left: 680px" }
    = link_to_remove_association 'remove step', f
    = link_to_add_association 'add video', f, :main_video_usage

_main_video_usage_fields.html.haml

.nested-fields
  = f.collection_select :video_id, Video.all.order(:title), :id, :title

回答1:

You can give an explicit order, use id or created_at if you want to keep the order of creation:

has_many :main_video_usage, -> { order('id asc') }, class_name: 'VideoUsage::Main', as: :parent