How to order included elements in Rails 3

Solution 1:

Try this in your Today model:

has_many :tasks, :order => 'priority DESC'

EDIT: As mentioned in comment below, in Rails 4+, this is now:

has_many :tasks, -> { order(:priority => :desc) }

(more info here)

Solution 2:

Direct solution would be to include the tasks table name before priority:

Today.where(:user_id => current_user.id).includes(:tasks).order('tasks.priority').first
# joins(:tasks) is not required

Or, if you don't want to have the table name hardcoded, you can merge with scope from Task model:

Today.where(:user_id => current_user.id).joins(:tasks).includes(:tasks).merge(Task.order(:priority)).first
# joins(:tasks) here is required

Also, you can add has_many: todays to User model to ditch the where clause and do:

current_user.todays.includes(:tasks).order('tasks.priority').first
# or
current_user.todays.joins(:tasks).includes(:tasks).merge(Task.order(:priority)).first

But if you need only/always to order by priority, and do not need other different orderings, adding order to has_many :tasks is easier.