# Kind of a complex find :order

**URL:** <https://www.ruby-forum.com/t/kind-of-a-complex-find-order/140780>\
**Category:** Rails\
**Created:** [June 18, 2008, 2:17pm UTC](https://www.ruby-forum.com/t/kind-of-a-complex-find-order/140780 "2008-06-18T14:17:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![differenthink](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/6bbea6/32.png) [@differenthink](https://www.ruby-forum.com/u/differenthink)\
**Post date:** [June 18, 2008, 2:17pm UTC](https://www.ruby-forum.com/t/kind-of-a-complex-find-order/140780/1 "2008-06-18T14:17:29Z")

</div>

Hi,

i ve got two models,  
“Question” and “Answer”  
A “question” can have many “answers”, or none.

I want to order my questions by answers date or question date if it  
has no answer,  
i tried to do that :

Question.find(:all, :order=\>“answers.date DESC, questions.date DESC”)

But questions without answers appear always after questions with  
answers, even when the question was created after an answer…

Could you give me an hints ?

Thanks a lot…

---

<div class="post-metadata">

**Author:** ![differenthink](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/6bbea6/32.png) [@differenthink](https://www.ruby-forum.com/u/differenthink)\
**Post date:** [June 19, 2008, 8:51pm UTC](https://www.ruby-forum.com/t/kind-of-a-complex-find-order/140780/2 "2008-06-19T20:51:21Z")

</div>

I think for this I would find all the questions (and eager load the  
answers for those questions) and then sort the array. e.g.

class Question \< ActiveRecord::Base  
has\_many :answers, :order =\> “answers.date DESC”

def latest\_date\_including\_answers  
if self.answers.blank?  
return self.date  
else  
return answers.first.date  
end  
end

def self.newest\_including\_answers  
find(:all, :include =\> :answers).sort{|a,b|  
a.latest\_date\_including\_answers \<=\>  
b.latest\_date\_including\_answers  
}  
end  
end

The latest\_date\_including\_answers method assumes that answers always  
come after the question is asked (since it doesnt compare answer.date  
to question.date).
