Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid Scope order by syntax please

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'
...
end
like image 448
kinet Avatar asked Jun 14 '11 03:06

kinet


1 Answers

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) }
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)
like image 91
RameshVel Avatar answered Oct 09 '22 13:10

RameshVel