# Order on virtual attribute in has\_many

**URL:** <https://www.ruby-forum.com/t/order-on-virtual-attribute-in-has-many/170862>\
**Category:** Rails\
**Created:** [June 23, 2009, 5:59pm UTC](https://www.ruby-forum.com/t/order-on-virtual-attribute-in-has-many/170862 "2009-06-23T17:59:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![harm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/b4bc9f/32.png) [@harm](https://www.ruby-forum.com/u/harm)\
**Post date:** [June 23, 2009, 5:59pm UTC](https://www.ruby-forum.com/t/order-on-virtual-attribute-in-has-many/170862/1 "2009-06-23T17:59:20Z")

</div>

Hi all,

Consider the following models:  
class Sheep \< AR::B  
belongs\_to :herd

def some\_virtual\_attribute  
#returns something sortable  
end  
end

class Herd \< AR::B  
has\_many :sheep do  
def some\_method  
#do something useful  
end  
end  
end

I want to be able to do:  
some\_herd.sheep.some\_method

But the collection sheep should be sorted on the  
some\_virtual\_attribute of Sheep.

I tried something along the line of:  
has\_many :sheep do  
def ordered  
sort {|a,b| a.some\_virtual\_attribute \<=\>  
b.some\_virtual\_attribute}  
end  
end

This however returns an instance of Array on which the ‘some\_method’  
is not defined. How can I solve this?

With kind regards,  
Harm

---

<div class="post-metadata">

**Author:** ![harm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/b4bc9f/32.png) [@harm](https://www.ruby-forum.com/u/harm)\
**Post date:** [June 24, 2009, 5:53pm UTC](https://www.ruby-forum.com/t/order-on-virtual-attribute-in-has-many/170862/2 "2009-06-24T17:53:49Z")

</div>

To get this to work, you’d need to return an AssociationCollection,  
which is going to be tricky. Association extensions aren’t _generally_  
combinable like this; I think you may be thinking about named scopes.

–Matt J.
