开发者

ruby on rails - sorting model collection with complex logic

开发者 https://www.devze.com 2023-03-20 07:34 出处:网络
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 (pe

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.


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")


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消