Are scopes just syntax sugar, or is there any real advantage in using them vs using class methods?
A simple example would be the following. They’re interchangeable, as far as I can tell.
scope :without_parent, where( :parent_id => nil )
# OR
def self.without_parent
self.where( :parent_id => nil )
end
What is each of the techniques more appropriate for?
EDIT
named_scope.rb mentions the following (as pointed out below by goncalossilva):
Line 54:
Note that this is simply ‘syntactic
sugar’ for defining an actual class
method
Line 113:
Named scopes can also have extensions,
just as with has_many declarations:
class Shirt < ActiveRecord::Base
scope :red, where(:color => 'red') do
def dom_id
'red_shirts'
end
end
end
For simple use cases, one can see it as just being syntax sugar. There are, however, some differences which go beyond that.
One, for instance, is the ability to define extensions in scopes:
In this case,
turn_blueis only available to red flowers (because it’s not defined in the Flower class but in the scope itself).