我如何使用 Rails 4 和 mongoind 与其他模型共享范围方法

How could I share scope method with other models using Rails 4 and mongoind

如何使用 Rails 4 和 mongoind

与其他模型共享作用域方法

如果把scope放在included do里,错误是

NoMethodError: undefined method `scope' for User:Class

如果把scope放在module ClassMethods里,错误是

NoMethodError: undefined method `scope' for RecentlySearch::ClassMethods:Module

代码片段

class User
  include RecentlySearch
  include Mongoid::Document
  field :history, type: Array
end

片段 2

module RecentlySearch
extend ActiveSupport::Concern

module ClassMethods
  scope :hi, -> {p 'hi'}
end

included do
  scope :hi, -> {p 'hi'}

end

结束

scope class 方法来自 Mongoid::Document 所以当你:

include RecentlySearch

还没有scope方法。您需要先包含 Mongoid::Document

include Mongoid::Document
include RecentlySearch