Rails中的范围与类方法3

Júl*_*tos 6 ruby-on-rails ruby-on-rails-3

范围只是语法糖,或者使用它们与使用类方法有任何实际优势吗?

一个简单的例子如下.据我所知,它们是可以互换的.

scope :without_parent, where( :parent_id => nil )

# OR

def self.without_parent
  self.where( :parent_id => nil )
end
Run Code Online (Sandbox Code Playgroud)

每种技术更适合什么?

编辑

named_scope.rb提到以下内容(如goncalossilva所述):

54行:

请注意,这只是用于定义实际类方法的"语法糖"

113行:

命名范围也可以具有扩展名,就像has_many声明一样:

class Shirt < ActiveRecord::Base
  scope :red, where(:color => 'red') do
    def dom_id
      'red_shirts'
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

gon*_*lva 11

对于简单的用例,人们可以将其视为语法糖.但是,有一些差异超出了这个范围.

例如,一个是在范围中定义扩展的能力:

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

在这种情况下,turn_blue仅可用于红色花朵(因为它没有在Flower类中定义,而是在范围本身中定义).