I am doing some maintenance on a Rails 2 application using Ruby 1.8.7. I am using will_paginate.
I have the following problem:
When calling current_user.products.paginate(:page => 1, :order => “updated_at asc“) it orders, as expected, based on the updated_at property in products.
However, when calling current_user.products.paginate(:page => 1, :order => “released_at asc“) it does not order on released_at as expected. In fact it doesn’t matter whether I specify ordering to happen according to “asc” or “desc”, I get the same collection returned.
updated_at and released_at are both attributes defined on the model and exists in the database and all values are non-null. There is no default_scope defined on the models.
What could be causing this and how to correct this?
Adding Desc products below (for brevity I am only listing the relevant fields):
| Field | Type | Null | Key | Default | Extra |
| released_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
The Product model inherits from a model that also defines the released_at attribute. The method for released_at is overloaded in the Ruby on Rails code so that if one would call product.released_at on an instance product of Product, then it would actually call the released_at value on the parent model. As a result, from the rails console it always looks as if released_at is not null and contains a value.
However, looking at the database directly shows that released_at is null in the Product model and as such, even though the will_paginate request goes through correctly, no ordering is done because the values are all the same (null). In the case where the exact same query is performed on the updated_at attribute, sorting works because that attribute is not null. I missed this because I checked for empty values from the Rails Console rather than in MySQL directly.
My solution was to define a named_scope on the Product model that sorts based on the value in the parent model. I then call the paginate function on the named scope.