【发布时间】:2014-01-03 00:43:37
【问题描述】:
code sn-p 有三种方法:lambda、scope 和class method。
它们都返回相同的结果。
问题:
-
Ruby/Rails中是否有任何最佳做法,当首选使用其中一种而不是另一种时? -
在什么情况下您会使用
lambda、scope或class方法(最佳实践)。class Cars < ActiveRecord::Base attr_accessible :manufacturer, :price, :used #one scope :used_and_cheap_lambda, lambda { where('used = ?', true ).where('price >= ?',30000) } #two scope :used_and_cheap_scope, where('used = ?', true ).where('price >= ?',30000) #three def self.used_and_cheap_class where('used = ?', true ).where('price >= ?',30000) end end Cars.used_and_cheap_lambda.count => #24 Cars.used_and_cheap_class.count => #24 Cars.used_and_cheap_scope.count => #24
【问题讨论】:
标签: ruby-on-rails ruby methods