Sort collection after associated resource's acts_as_tree/acts_as_list order

154 Views Asked by At

I have a SuccessCriterion model that implements both acts_as_tree and acts_as_list so it can be arranged as sorted tree hierarchy. Every success criterion can has many Boilerplate objects.

class SuccessCriterion < ActiveRecord::Base
  has_many :boilerplates

  acts_as_tree order: :position, dependent: :restrict_with_error
  acts_as_list scope: [:parent_id]
end

class Boilerplate < ActiveRecord::Base
  belongs_to :success_criterion
end

I can retrieve an flat array of all the success criteria sorted correctly by calling SuccessCriterion.collection_tree.

Now when listing the boilerplates, I want them ordered by the hierarchy of the success criteria. What's the easiest way to do this? I think I have to manually sort the collection using Ruby, but I'm unsure how to do it.

Update

My first try is the following, but it feels a bit clumsy:

def index
  # @boilerplates is provided by ransack

  ordered_boilerplates = []

  SuccessCriterion.collection_tree.each do |success_criterion|
    ordered_boilerplates += @boilerplates.select do |boilerplate|
      boilerplate.success_criterion_id == success_criterion.id
    end
  end

  ordered_boilerplates += @boilerplates.select do |boilerplate|
    boilerplate.success_criterion_id.nil?
  end

  @boilerplates = ordered_boilerplates
end
0

There are 0 best solutions below