This project is archived and is in readonly mode.
Inconsistent behavior using "order" in scopes
-
javierm
Sooner than I expected, here's the failing test.
-
Neeraj Singh
- Milestone set to 3.x
- State changed from new to open
- Assigned user set to Neeraj Singh
- Tag set to rails 3
- Importance changed from to Low
-
Neeraj Singh
I have a fix for this one. However my fix is breaking a number of tests. Here I am discussing one of the tests that is failing because of my fix.
Let's start from the beginning. We have a model which looks like this.
class DeveloperOrderedBySalary < ActiveRecord::Base self.table_name = 'developers' default_scope :order => 'salary DESC' scope :by_name, :order => 'name DESC' scope :reordered_by_name, reorder('name DESC') def self.all_ordered_by_name with_scope(:find => { :order => 'name DESC' }) do find(:all) end end endNow the question is what kind of sql should be generated for the following case
DeveloperOrderedBySalary.all_ordered_by_nameThe existing rails edge code would produce following sql
SELECT "developers".* FROM "developers" ORDER BY name DESCI also happen to think that above sql is wrong. It is wrong because it does not take into account the default_scope. default_scope is always applied as the very first thing. And if the default_scope dictates order then that order should be followed. Notice that with_scope obeys default_scope in general, but in this case with_cope is NOT obeying default_scope.
After my fix the sql generated is
SELECT "developers".* FROM "developers" ORDER BY salary DESC, name DESCAs I said earlier my fix for this issue is breaking a lot of tests similar to the case illustrated. I would like to have an opinion from a core team member on this topic.
-
Neeraj Singh
Current behavior in rails 2-3-stable is
class User < ActiveRecord::Base default_scope :order => 'created_at desc' named_scope :custom, :order => 'name desc' end > User.all SELECT * FROM "users" ORDER BY created_at desc > User.custom SELECT * FROM "users" ORDER BY name desc -
Santiago Pastorino
- Milestone cleared.
- Assigned user changed from Neeraj Singh to Santiago Pastorino
Neeraj only to write a bit of the progress we did on this. We have a patch and Neeraj is writing some tests.
-
Santiago Pastorino
- State changed from open to committed
