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
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”.
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 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.
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.
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_blue
is only available to red flowers (because it's not defined in the Flower class but in the scope itself).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With