2011-06-16 36 views
6

作用域只是語法糖,還是在使用它們和使用類方法時有任何真正的優勢?Rails 3中的作用域vs類方法

一個簡單的例子如下。就我所知,它們是可以互換的。

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

# OR 

def self.without_parent 
    self.where(:parent_id => nil) 
end 

什麼是每種技術更適合?

EDIT

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 
+1

示波器的問題是它們有時可能擠在模型的頂部。我相當肯定他們只是語法糖。使用rails 3延遲加載時,你沒有理由不能像你指出的那樣使用類方法。在這一點上,它確實歸結爲一個偏好問題。 – agmcleod 2011-06-16 17:21:26

+0

Platsformatec在http://blog.plataformatec.com.br/2013/02/active-record-scopes-vs-class-methods/ – caspyin 2014-03-17 13:12:23

回答

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 

在這種情況下,turn_blue僅提供給紅花草(因爲它不是在花類,但在本身的範圍界定)。

+1

Uuh,這是非常好的:) *啓動控制檯* – 2011-06-16 17:38:55