Scopes vs class methods in Rails 3

Are areas just syntactic sugar, or is there a real advantage in using them against class methods?

A simple example would be the following. As far as I know, they are interchangeable.

scope :without_parent, where( :parent_id => nil ) # OR def self.without_parent self.where( :parent_id => nil ) end 

Which of these methods is more suitable?

EDIT

named_scope.rb mentions the following (as indicated below by goncalossilva ):

Line 54 :

Please note that this is just “syntactic sugar” to determine the actual class. Method

Line 113 :

Named scopes can also have extensions, as with has_many declarations:

 class Shirt < ActiveRecord::Base scope :red, where(:color => 'red') do def dom_id 'red_shirts' end end end 
+6
source share
1 answer

For simple use cases, you can see that it is just syntactic sugar. There are, however, some differences that go beyond this.

One of them, for example, is the ability to define extensions in scope:

 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 available only for red flowers (because it is not defined in the Flower class, but in the region itself).

+11
source

Source: https://habr.com/ru/post/890701/


All Articles