Let's say I have a User
with a field name
, and which has_many teams
, and a Team
that belongs_to a user
, and belongs_to a sport
. A Sport
has a field name
and has_many teams
.
I want to walk through the sports
, do some stuff, and collect an array of the teams
sorted by the name
of the user
.
result = []
Sport.asc(:name).each do |spt|
# some other stuff not relevant to this question but that
# justifies my looping through each sport.
spt.teams.asc(:'user.name').each { |t| result << t }
end
This runs but and the sorting of the sports
is as expected, but the order of the teams in result
is not sorted as I'd expect.
What is the correct way, using Mongoid
to sort a collection by the value of a relation?