Take the 2-minute tour ×

I'm using the latest mongoid...

How do I do the mongoid equivalent of this active record named_scope:

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

  embedded_in :post

  field :body, :type => String

  named_scope :recent, :limit => 100, :order => 'created_at DESC'
share|improve this question
add comment

1 Answer

up vote 27 down vote accepted

It has to be defined like this

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

You can check out the mongoid documentation for scopes here

From the page

Named scopes are defined at the class level using a scope macro and can be chained to create result sets in a nice 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) }

# Find all the rockstars.

# Find all rockstars that should probably quit.

# Find a criteria with Keith Richards in it.
share|improve this answer
add comment

Your Answer


