加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails中的范围与类方法3

发布时间:2020-12-16 23:01:33 所属栏目:百科 来源:网络整理
导读:范围只是语法糖,或者使用它们与使用类方法有任何实际优势吗? 一个简单的例子如下.据我所知,它们是可以互换的. scope :without_parent,where( :parent_id = nil )# ORdef self.without_parent self.where( :parent_id = nil )end 每种技术更适合什么? 编辑
范围只是语法糖,或者使用它们与使用类方法有任何实际优势吗?

一个简单的例子如下.据我所知,它们是可以互换的.

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

# OR

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

每种技术更适合什么?

编辑

named_scope.rb提到以下内容(如下文goncalossilva所述):

54行:

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

113行:

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

解决方法

对于简单的用例,人们可以将其视为语法糖.但是,有一些差异超出了这个范围.

例如,一个是在范围中定义扩展的能力:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读