请按语法订购Mongoid Scope

时间:2011-06-14 03:26:26

标签: ruby-on-rails mongodb scope mongoid named-scope

我正在使用最新的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

1 个答案:

答案 0 :(得分:35)

必须像这样定义

scope :recent, order_by(:created_at => :desc).limit(100)

您可以查看范围here

的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)