简体   繁体   English

Rails中的范围与类方法3

[英]Scopes vs class methods in Rails 3

Are scopes just syntax sugar, or is there any real advantage in using them vs using class methods? 范围只是语法糖,或者使用它们与使用类方法有任何实际优势吗?

A simple example would be the following. 一个简单的例子如下。 They're interchangeable, as far as I can tell. 据我所知,它们是可以互换的。

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

# OR

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

What is each of the techniques more appropriate for? 每种技术更适合什么?

EDIT 编辑

named_scope.rb mentions the following (as pointed out below by goncalossilva ): named_scope.rb提到以下内容(如goncalossilva所述 ):

Line 54 : 54行

Note that this is simply 'syntactic sugar' for defining an actual class method 请注意,这只是用于定义实际类方法的“语法糖”

Line 113 : 113行

Named scopes can also have extensions, just as with has_many declarations: 命名范围也可以具有扩展名,就像has_many声明一样:

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

For simple use cases, one can see it as just being syntax sugar. 对于简单的用例,人们可以将其视为语法糖。 There are, however, some differences which go beyond that. 但是,有一些差异超出了这个范围。

One, for instance, is the ability to define extensions in scopes: 例如,一个是在范围中定义扩展的能力:

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 only available to red flowers (because it's not defined in the Flower class but in the scope itself). 在这种情况下, turn_blue仅适用于红色花朵(因为它没有在Flower类中定义,而是在范围本身中定义)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM