Thursday, April 3, 2008

Eager Loading + Order By

So I was trying to cut down on the number of queries that I was making on a particular page and ran into a slight problem.

Basically, I had a relationship where a User has many Notifications:

class User
has_many :notifications, :order => 'created_at DESC'
end

In my controller, I wanted to cut down on the queries, so I did some eager loading:

@user = User.find(user_id, :include => :notifications)

However, when I went to go view my page, the notifications were not in the order as I specified. I went to go take a look at the query, and lo-and-behold, there was no ORDER BY stated in the query.

After some thought, it became apparent why no ORDER BY was included. This makes sense because if you eager load many tables, each with its own ORDER BY, it would be difficult, if not impossible, to have everything returned properly.

I would assume, without much thought, that one would assume that this would work. With further thought though, this becomes the correct thing to do.

Just a heads up ;)


W

No comments: