Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the real benefit of scopes

I've looked at over 10 pages trying to find the benefit of a scope over any other ActiveRecord class method that returns an ActiveRecord::Relation.

In the following for example why are scopes better than the alternative below it which do the same thing:

  #scope :pat1,  lambda {{:conditions => ["name like ?", 'J%']}}    
  #scope :pat2,  lambda {{:conditions => ["id  > 5"]}}  

  def self.pat1
    where("name like ?", 'J%')
  end  

  def self.pat2 
    where("id  > 5")
  end  

  def patx 
    self.class.pat1.pat2.first
  end

The documentation over and over again says that scopes are beneficial because they can be chained...

"All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it." -guides.rubyonrails.org

"The main reason scopes are better than plain class methods is that they can be chained with other methods" http://ruby.railstutorial.org

...but the alternative above can also be chained producing the same results.

Just trying to figure out if there's an emperor's new clothes thing going on here. Even from a syntactic standpoint there appears to be no benefit. Are they faster- some sources vaguely suggest that.

like image 875
Mark Avatar asked Mar 15 '12 21:03

Mark


1 Answers

ActiveRecord scopes are really just syntax sugar wrapped in a best practice, as noted already.

In the 2.x days of Rails, when they were called "named_scope", they mattered a bit more. They allowed easy chaining of conditions for generating a query. With the improvements in Rails 3.x with Arel, it is simple to create functions for query relations, as you noted. Scopes just provide a simple and elegant solutions for chainable, predefined queries. Having all the scopes at the top of a model improves the readability and helps shows how the model is used.

like image 152
mguymon Avatar answered Oct 13 '22 00:10

mguymon