1

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
Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152
  • I'm not too familiar with `act_as_tree`, but the [source documentation](https://github.com/amerine/acts_as_tree/blob/master/lib/acts_as_tree.rb#L59) mentions that the `order` attribute *makes it possible to sort the children according to this SQL snippet.* Might be worth investigating. – zwippie Jan 18 '16 at 17:33

0 Answers0