0

I've got a method that sorts a collection by an array of ids like so:

def selected_components
  ids = @document.publications.rank(:position).map(&:component_id)
  Component.find(ids).sort_by { |c| ids.index(c.id) }
end

This works fine, but I want to sort the result by the order of ids as efficiently as possible. Apparently my method is not the most efficient, although I'm not 100% why that is.

Why isn't this so efficient? Any advice? Thanks so much.

1 Answer 1

1

I'm pretty sure: if you search for efficiently, you must let the db do the work.

First, eager load publications with its components:

@document = Document.includes(publications: :component).find_by(...)

Then rank and map the components:

def selected_components
  @document.publications.rank(:position).map(&:component)
end

Now, selected_components don't need to do db access. Also, you don't need to sort data two times, only one (in rank).

Edited: Eager load, its recomended as a best practice to fix the n + 1 issue here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.