# Why doesn't named\_scope sort properly?

**URL:** <https://discuss.rubyonrails.org/t/why-doesnt-named-scope-sort-properly/34929>\
**Category:** rubyonrails-talk\
**Created:** [October 1, 2008, 6:34pm UTC](https://discuss.rubyonrails.org/t/why-doesnt-named-scope-sort-properly/34929 "2008-10-01T18:34:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rails\_in\_dc](https://avatars.discourse-cdn.com/v4/letter/r/c0e974/32.png) [@rails\_in\_dc](https://discuss.rubyonrails.org/u/rails_in_dc)\
**Post date:** [October 1, 2008, 6:34pm UTC](https://discuss.rubyonrails.org/t/why-doesnt-named-scope-sort-properly/34929/1 "2008-10-01T18:34:10Z")

</div>

I have this simple named\_scope that returns all Events after a given id:

named\_scope :recent\_by\_id, lambda {|id| { &nbsp;&nbsp;&nbsp;&nbsp;:conditions =\> ['id \> ?', id], :order =\> 'id ASC' }}

The problem is that named\_scope returns a query with an order by clause containing created\_at first: ORDER BY created\_at DESC, id ASC

How do I get named\_scope to ignore the created\_at and simply give me a query sorted by id?

best,

- Matt

---

<div class="post-metadata">

**Author:** ![Ramon](https://avatars.discourse-cdn.com/v4/letter/r/34f0e0/32.png) [@Ramon](https://discuss.rubyonrails.org/u/Ramon)\
**Post date:** [October 1, 2008, 10:34pm UTC](https://discuss.rubyonrails.org/t/why-doesnt-named-scope-sort-properly/34929/2 "2008-10-01T22:34:08Z")

</div>

Yes this should work... maybe the other have an idea.

I have a tip though (it doesn't answer your question):

separate that into two named scopes: recent and by\_id so that you can do Model.recent(id).by\_id

More flexible.

Ramon Tayag

---

<div class="post-metadata">

**Author:** ![11175](https://avatars.discourse-cdn.com/v4/letter/1/8edcca/32.png) [@11175](https://discuss.rubyonrails.org/u/11175)\
**Post date:** [October 3, 2008, 7:51pm UTC](https://discuss.rubyonrails.org/t/why-doesnt-named-scope-sort-properly/34929/3 "2008-10-03T19:51:08Z")

</div>

I just created a super simple prototype app to test this out:

I created a Post model:

class Post \< ActiveRecord::Base &nbsp;&nbsp;named\_scope :recent\_by\_id, lambda { |id| { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:conditions =\> ['id \> ?', id], :order =\> 'id ASC' } } end

$ ./script/console Loading development environment (Rails 2.1.1)

> > posts = Post.recent\_by\_id(1)

Development Log: SELECT \* FROM "posts" WHERE (id \> 1) ORDER BY id ASC

Are you sure you are not including the :order somewhere else? This seems to work as expected.

Matt Constantine wrote:
