deruse
deruse

Reputation: 2881

ruby on rails - sorting model collection with complex logic

I have a collection of a model. I want to perform some complex sorting logic on this collection. The logic is not as simple as sorting based on a simple attribute. What the best way (performance and maintainability wise) to perform complex sorting logic on a collection of models. I am thinking along the lines of passing in a block to the sort method? But I am not sure...

Thanks.

Upvotes: 2

Views: 1713

Answers (2)

Chubas
Chubas

Reputation: 18033

Yes, you can use a block using sort_by

@people.sort_by { |person| person.age }

sort_by uses the Schwartzian transform internally in sort_by, so if your logic is a little more complex than that, you can still create a scoring function and pass it to sort_by

@people.sort_by do |person|
  tier = if person.deceased?
    2
  elsif !person.important?
    1
  else
    0
  end
  [tier, person.age
end

Ask yourself if you can't make the sorting directly from the SQL query, this will be a lot faster (assuming the right query and indices)

@people = Person.all(:select => "*, (age + popularity) as coolness", :order => "coolness")

Upvotes: 4

apneadiving
apneadiving

Reputation: 115511

I'd advise you to read this resource, this chapter in particular:

#21 Using Procs for Filtering (matching_members.rb)

There are great filtering examples given using Procs and blocks.

PS: yes I'd use blocks even if your question is a bit vague.

Upvotes: 1

Related Questions