# Named\_scope and ordering

**URL:** <https://www.ruby-forum.com/t/named-scope-and-ordering/133881>\
**Category:** Rails\
**Created:** [April 4, 2008, 4:18pm UTC](https://www.ruby-forum.com/t/named-scope-and-ordering/133881 "2008-04-04T16:18:21Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tim](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ce73a5/32.png) [@tim](https://www.ruby-forum.com/u/tim)\
**Post date:** [April 4, 2008, 4:18pm UTC](https://www.ruby-forum.com/t/named-scope-and-ordering/133881/1 "2008-04-04T16:18:21Z")

</div>

Hi,

this is a general design question and I liked to see how other people  
handle the following situation: Before named\_scope I wrote custom  
finders for my model classes. Something like

# order.rb

class Order \< ActiveRecord::Base  
class \<\< self  
def find\_all\_marked  
find(:all, :conditions =\> {:marked =\> 1}, :order =\> ‘name ASC’)  
end  
end  
end

Now this can easily be refactored to

class Order \< ActiveRecord::Base  
named\_scope :marked, :conditions =\> {:marked =\> 1}, :order =\> ‘name  
ASC’  
end

While the find\_all\_marked method (to me) felt simple enough to include  
an :order option, the same thing just feels wrong in the named\_scope.  
I mean I knew exactly where I would be calling that method from, but  
named scopes can be combined and are very flexible. Especially they do  
not behave very intuitively when combining two names scopes that  
include an :order option:

# order.rb

named\_scope :active, :condtitions =\> …, :order =\> ‘created\_at DESC’

Order.marked.active # ordered by ‘name ASC’ according to the first  
scope ‘marked’

So what are the options?

# orders\_controller.rb

def index  
@marked = Order.marked.find(:all, :order =\> ‘name ASC’)  
end

No, that feels like bleeding model code into the controller.

# order.rb

named\_scope :ordered\_by\_name, :order =\> ‘name ASC’

# orders\_controller.rb

@marked = Order.marked.ordered\_by\_name

Still my best idea yet, but also quite verbose. It would be nice if  
you could define a default order for a named\_scope and then you could  
use ‘ordered\_by\_’-scopes to override. But the naive approach fails  
here, because the order of the first scope takes priority over any  
following.

How do you handle this situation?

Regards,  
Tim
