Why doesn't named_scope sort properly?

I have this simple named_scope that returns all Events after a given
id:

named_scope :recent_by_id, lambda {|id| {
: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

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 T.

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

I created a Post model:

class Post < ActiveRecord::Base
named_scope :recent_by_id, lambda { |id| {
: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 C. wrote:

I have this simple named_scope that returns all Events after a given
id:

named_scope :recent_by_id, lambda {|id| {
: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