簡體   English   中英

Rails中的范圍與類方法3

[英]Scopes vs class methods in Rails 3

范圍只是語法糖,或者使用它們與使用類方法有任何實際優勢嗎?

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

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

# OR

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

每種技術更適合什么?

編輯

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

對於簡單的用例,人們可以將其視為語法糖。 但是,有一些差異超出了這個范圍。

例如,一個是在范圍中定義擴展的能力:

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僅適用於紅色花朵(因為它沒有在Flower類中定義,而是在范圍本身中定義)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM