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
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.
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.
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.
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
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
has_many :users, -> { order(:last_name, :first_name) }, :through => :assignments, source: 'user'