I have a User model in which
default_scope :order => 'created at desc'
I currently have fifty records, ids 1 through 50.
User.first returns User id: 50.
User.first(2) returns User id: 50 and User id: 49
User.last returns User id: 1
This all makes sense. However,
User.last(2) returns User id: 49 and User id: 50, in that order. Why is that? And how do I return User id: 1 and User id: 2?
This is a common mistake.
User.last(1)andUser.last()are not exactly same.User.last(1)would give you an array of a single record whileUser.last()would return that record object.Again, both these methods would behave entirely differently if you have a
default_scopein your User model.User.lastjust works on your default scope, reversing its order. So the SQL query it fires is:On the other hand,
User.last(1)is similar to writingUser.order('id desc').limit(1). And with yourdefault_scopein action, theorder by id descwould come second to the default one. So the SQL it fires would be:So what you really need to do here is remove the default scope using
User.unscopedas Kien has mentioned.Personally, I avoid using default scope ordering and use explicit scoping instead.