Julio Santos
Julio Santos

Reputation: 3895

Scopes vs class methods in Rails 3

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

Upvotes: 6

Views: 1437

Answers (1)

goncalossilva
goncalossilva

Reputation: 1860

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:

class Flower < ActiveRecord::Base
  named_scope :red, :conditions => {:color => "red"} do
    def turn_blue
      each { |f| f.update_attribute(:color, "blue") }
    end
  end
end

In this case,turn_blueis only available to red flowers (because it's not defined in the Flower class but in the scope itself).

Upvotes: 11

Related Questions