Rails 3 中的作用域与类方法 [英] Scopes vs class methods in Rails 3

查看:45
本文介绍了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

每种技术更适合什么?

编辑

named_scope.rb 提到了以下(如下面的 goncalossilva 指出):

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

54:

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

Note that this is simply 'syntactic sugar' for defining an actual class method

113:

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

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

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

在这种情况下,turn_blue仅适用于红色花朵(因为它不是在 Flower 类中定义,而是在作用域本身中定义).

In this case,turn_blueis only available to red flowers (because it's not defined in the Flower class but in the scope itself).

这篇关于Rails 3 中的作用域与类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆