I want to sort an array of objects by the objects last_name, but always put a certain object in the first position of the array.
To achieve that I already tried a lot but always failed with the resulting structure of the array. Here is one of my tries which fails because I can’t run any methods on the resulting array objects (e.g. @team.each do |m| puts m.username end fails):
if @team = UserGroup.find_by_name("team").users.sort_by(&:last_name)
if first_member = @team.detect{|m| m.username == "test"}
@team.unshift @team.reject{|m| m.username == "test"}
end
end
Thanks for your help.
You can use SQL’s ORDER BY capabilities, faster than Ruby (btw, you should use
find_by_attribute!). Untested, but play with something like this:Of course you can use Ruby with the same idea: