我想在 Mongoid 中定义 2 种方法:昂贵?及其适用范围。这是我正在做的事情:
class MyItem
include Mongoid::Document
include Mongoid::Timestamps
# it could find expensive and cheap items depending of is_expensive parameter
scope :expensive, ->(is_expensive = true) do
if is_expensive
where(:expensive?)
else
not_in(:expensive?)
end
end
def expensive?
price >= 10 # $10
end
end
所以我希望能够通过以下方式找到项目:
MyItem.expensive #find all expensive ones
MyItem.where(:expensive?) #the same as above
MyItem.first.expensive? #check if it's expensive
items.expensive # items is the collection of MyItem
他们不工作。例如,MyItem.where(:expensive?)
说undefined method each_pair for :expensive?:Symbol
特别是我想弄清楚如何做将作为实例方法(不是类方法)工作的方法或范围 -items.expensive