views:

353

answers:

1

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?

+2  A: 

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

The Tailor