Thursday, 9 April 2015

Mongoid scopes usage

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 :age_or_occupation, ->  {any_of({occupation: "Rockstar"}, {age: 18}) }
  scope :over, ->(limit) { where(:age.gt => limit) }
end

# Find all the rockstars.
Person.rock_n_rolla

# Find all rockstars age greater than 30.
Person.washed_up.rock_n_rolla

# Find all rockstars or other persons have their age as 18 (or operation)
Person.age_or_occupation

# Find a criteria rockstart with 60 as their aget.
Person.rock_n_rolla.over(60)

No comments:

Post a Comment