ruby-on-rails - 请按语法排序 Mongoid Scope

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

我用的是最新的mongoid...

我该如何做这个名为_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

最佳答案

必须这样定义

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

您可以查看范围的 mongoid 文档 here

从页面

命名作用域是在类级别使用作用域宏定义的,并且可以链接起来以在良好的 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)

关于ruby-on-rails - 请按语法排序 Mongoid Scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6338752/

相关文章:

C++ "was not declared in this scope"在派生类中覆盖纯虚方法时

javascript - 如何在作为成功回调传递给 getJSON 的方法中引用我的对象?

scope - BizTalk 表达式形状内的范围是什么?

Javascript 代码在 Ruby on Rails 中不起作用

node.js - 如何使用mongodb和AWS存储文件

mongodb - 多个集合包含数千个文档还是一个集合包含 1 亿个文档更好?

C# MongoDB反序列化id属性

ios - 无法在mac中使用OpenALPR库生成openaplr.framework

ruby-on-rails - 从 Redis::TimeoutError 中恢复

ruby-on-rails - 如何在验证期间将 ivars 插入 Rails i18n 字符串?