glm4
glm4

Reputation: 303

ActiveAdmin has_many with custom collection order

Given the following models:

class WorkoutProgram < ApplicationRecord
  has_many :workouts, dependent: :destroy
end

class Workout < ApplicationRecord
  belongs_to :workout_program
end

Is there any way to set a custom order in ActiveAdmin has_many input? I don't want to enable drag & drop so sortable is not an option. The idea is to show the workouts in the same order they were added when editing a WorkoutProgram.

As a workaround I am using another has_many relation in WorkoutProgram only for this purpose. So I added to the model:

has_many :ordered_workouts, -> { ordered_by_id },
           class_name: Workout.to_s, dependent: :destroy, inverse_of: :workout_program

and then used it in the ActiveAdmin page like this:

form.has_many :ordered_workouts, allow_destroy: true do...

Upvotes: 3

Views: 1442

Answers (1)

chumakoff
chumakoff

Reputation: 7044

You can do that like this:

form.has_many :workouts, for: [:workouts, form.object.workouts.ordered_by_id] #, ...

Upvotes: 7

Related Questions