Sort-weirdness - active record issue?


#1

I’m selecting data into a controller and sorting it. The code (in the
controller) looks like this:

def index
@assignments = []
tasks = Task.find(:all, :conditions => [“person_id = ? and
actual_end_date is null”, session[:user].id.to_s ])
issues = Issue.find(:all, :conditions => [“person_id = ? and
status
<> ‘closed’” , session[:user].id.to_s] )
@assignments.concat(tasks)
@assignments.concat(issues)
@assignments= @assignments.sort
@assignments.each {|ea| puts ea.name +
ea.scheduled_end_date.to_s}
end

The output from the puts statement is this:
P2 Task1 2006-03-16
T2 2006-03-23
Test Task 2006-01-05
super tests 2006-01-19
super test 3 2006-01-26
Larry’s issue 2006-03-09

For some reason, the sort algorithm thinks that all the dates are nil so
they don’t get sorted, but they’re there as the puts shows. The sort
method
is below. When i didn’t include the check for nil in it, it threw an
exception, saying nil doesn’t understand <=>.

# Sort by due date (scheduled_end_date)
def <=> aTask
      @scheduled_end_date.nil? ? -1 : @scheduled_end_date <=>

aTask.scheduled_end_date
end

Any ideas would be greatly appreciated.


#2

@assignments= @assignments.sort {|a,b| a.scheduled_end_date <=>
b.scheduled_end_date}


#3

Hi Larry,

Try this:

tasks = Task.find_by_person_id session[:user].id, :order =>
‘scheduled_end_date DESC’ # or ASC for ascending

Hope that helps (you may want to fire up the console using ‘script/
console’ and try out diffrent queries)

Matt


#4

that works. Thank you.

But Why? I thought the two approaches were equivilent.


#5

I need to concatenate the results from two tables before sorting, so
this
doesn’t work.