请按语法订购Mongoid Scope

kin*_*net 18 scope named-scope ruby-on-rails mongodb mongoid

我正在使用最新的mongoid ......

我如何做这个活动记录named_scope的mongoid等价物:

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :post

  field :body, :type => String

  named_scope :recent, :limit => 100, :order => 'created_at DESC'
...
end
Run Code Online (Sandbox Code Playgroud)

Ram*_*Vel 35

它必须像这样定义

scope :recent, order_by(:created_at => :desc).limit(100)
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看范围的mongoid文档

从页面

命名范围是使用范围宏在类级别定义的,并且可以链接以在不错的DSL中创建结果集.

class Person
  include Mongoid::Document
  field :occupation, type: String
  field :age, type: Integer

  scope :rock_n_rolla, where(occupation: "Rockstar")
  scope :washed_up, where(:age.gt => 30)
  scope :over, ->(limit) { where(:age.gt => limit) }
end

# Find all the rockstars.
Person.rock_n_rolla

# Find all rockstars that should probably quit.
Person.washed_up.rock_n_rolla

# Find a criteria with Keith Richards in it.
Person.rock_n_rolla.over(60)
Run Code Online (Sandbox Code Playgroud)