Given the following AR models, I would like to sort users alphabetically by last name when given a handle to a task:
#user
has_many :assignments
has_many :ta
The M.G.Palmer's
approach works well, however table name is involved. There is a better way to do it:
has_many :users, :through => :assignments, :order => [ :last_name, :first_name ]
This works for me (Rails 4.2)
Applying an ordering on the through map is not preserved, aka this is not enough to have the genres ordered:
has_many :disk_genre_maps,
-> {order('disk_genre_map.sort_order')},
:inverse_of => :disk,
:dependent => :destroy,
:autosave => true
has_many :genres, # not sorted like disk_genre_maps
:through => :disk_genre_maps,
:source => :genre,
:autosave => true
So I overwrite this per instance:
def genres # redefine genres per instance so that the ordering is preserved
self.disk_genre_maps.map{|dgm|dgm.genre}
end
To make that work for assignments, this should be something like this (untested)
def genres= some_genres
self.disk_genre_maps = some_genres.map.with_index do |genre, index|
DiskGenreMap.new(disk:self, genre:genre, sort_order:index)
end
end