Rails中的范围与类方法3

时间:2011-06-16 17:13:54

标签: 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

每种技术更适合哪种?

修改

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 个答案:

答案 0 :(得分: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仅适用于红色花朵(因为它没有在Flower类中定义,而是在范围本身中定义)。