How do I order a has_many through association in Ruby on Rails?

Ruby on-RailsHas Many-Through

Ruby on-Rails Problem Overview


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 :tasks, :through => :assignments    

#assignment
belongs_to :task
belongs_to :user

#task
has_many :assignments
has_many :users, :through => :assignments

I would like to get a task then navigation to its assigned users, and sort the user list alphabetically.

I keep thinking that I should be able to add the :order clause to has_many :users, :through => :assignments like this:

#task.rb
has_many :assignments
has_many :users, :through => :assignments, :order => 'last_name, first_name'

however this does not work.

How can I sort users by last_name when given a task?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Since condition arguments are deprecated in Rails 4, one should use scope blocks:

has_many :users, -> { order 'users.last_name, users.first_name' }, :through => :assignments

Solution 2 - Ruby on-Rails

Rails 3.x version:

has_many :users, :through => :assignments, :order => 'users.last_name, users.first_name'

UPDATE: This only works in Rails 3.x (maybe before that too). For 4+, see other answers.

Solution 3 - Ruby on-Rails

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 ]

Solution 4 - Ruby on-Rails

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

Solution 5 - Ruby on-Rails

I am using Rails (5.0.0.1) and could make the sort with this syntax in my model Group that has many users through group_users:

# Associations.
has_many :group_users
has_many :users, -> { order(:name) }, through: :group_users

Adjust the code to your need that will work.

Solution 6 - Ruby on-Rails

Would this work for you?

# User.rb

class User < ActiveRecord::Base
 default_scope :order => 'last_name ASC'
 ...
end

You can define other named scopes for when sorting needs to be different.

http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

Solution 7 - Ruby on-Rails

You could also create a new 'sort_order' column on the assignment table, and add a default scope like

default_scope { order('sort_order desc')}

to your assignments model.

Solution 8 - Ruby on-Rails

has_many :users, -> { order(:last_name, :first_name) }, :through => :assignments, source: 'user'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrswolffView Question on Stackoverflow
Solution 1 - Ruby on-RailsDanielView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMartin T.View Answer on Stackoverflow
Solution 3 - Ruby on-Railsdenis.peplinView Answer on Stackoverflow
Solution 4 - Ruby on-RailsedxView Answer on Stackoverflow
Solution 5 - Ruby on-RailsRicardo EmersonView Answer on Stackoverflow
Solution 6 - Ruby on-RailsAntony SastreView Answer on Stackoverflow
Solution 7 - Ruby on-RailsYogzzzView Answer on Stackoverflow
Solution 8 - Ruby on-Railsuser223697View Answer on Stackoverflow