2012-03-19 50 views
2

使用不同我有以下模式:Mongoid - 在範圍

class Message 
    include Mongoid::Document 

    field :tags,  :type => Array 

    scope :contained_tags, distinct(:tags) 
end 

由於distinct語法不是模型的方法,而是一個Criteria。因此上面的模型引發了異常undefined method 'distinct' for Message:Class (NoMethodError)

有沒有辦法做到這一點?

+0

'all.distinct(:tags)'? – rubish 2012-03-19 09:04:52

回答

1

你可以這樣做:

def self.contained_tags 
    scoped.distinct(:tags) 
end 
  1. 它的作用究竟作爲一個範圍
  2. ,你甚至可以鏈範圍;例如:

    Message.only_active.contained_tags

注:如果您使用的是mongoid和舊版本的 '作用域' 你不工作,然後使用:criteria.distinct(:tags)