我想在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