Mongoid Scope order by syntax please
Asked Answered
M

1

18

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
Mucilage answered 14/6, 2011 at 3:26 Comment(0)
H
36

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)
Hammertoe answered 14/6, 2011 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.