Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 682
Julio Santos Avatar asked Jun 16 '11 17:06

Julio Santos


People also ask

What is the difference between scope and class method Rails?

Scopes are just class methods. Internally Active Record converts a scope into a class method. "There is no difference between them" or “it is a matter of taste”.

When should you use scope methods in Rails?

Which one to prefer? It's all about consistency. Scopes are usually used when the logic is very small or, for simple where/order clauses. Class methods are used when it involves a bit more complexity, and when we need a finer grain of control over the execution of queries.

What are scopes in Rails?

What is a scope in Rails & why is it useful? Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code.

What are class methods in Rails?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition.


1 Answers

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).

like image 121
goncalossilva Avatar answered Nov 10 '22 00:11

goncalossilva