public
Last active

  • Download Gist
mongoid_sti_pets.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
require 'rubygems'
puts ENV["GEM_HOME"]
require 'mongoid'
require 'mongoid/version'
 
puts "Using Mongoid: #{Mongoid::VERSION}"
 
Mongoid.master = Mongo::Connection.new.db("mongoid_playground")
 
class Animal
include Mongoid::Document
field :name, :type => String
end
 
class Dog < Animal
end
 
class Cat < Animal
end
 
 
Animal.delete_all
Dog.delete_all
Cat.delete_all
 
Animal.create :title => "animal1"
Animal.create :title => "animal2"
Dog.create :title => "fido"
Dog.create :title => "rex"
Cat.create :title => "mittens"
Cat.create :title => "arnold schwarzenegger"
 
# get all the animals
results = Animal.all
puts "\n\nAnimal.all gives #{results.count} records matching all Animal documents (including cats and dogs):"
results.entries.each{|r| puts r.inspect }
 
# get all the dogs
results = Dog.all
puts "\n\nDog.all gives #{results.count} records matching just Dog documents:"
results.entries.each{|r| puts r.inspect }
 
# get all the cats
results = Cat.all
puts "\n\nCat.all gives #{results.count} records matching just Cat documents:"
results.entries.each{|r| puts r.inspect }
 
# get all the animals (specifically Animal)
results = Animal.criteria.type("Animal")
puts "\n\nAnimal.criteria.type(\"Animal\") gives #{results.count} records of only exact match type Animal (not including dogs and cats):"
results.entries.each{|r| puts r.inspect }
 
# get all the dogs again (specifically from Animal)
results = Animal.criteria.type("Dog")
puts "\n\nAnimal.criteria.type(\"Dog\") gives #{results.count} records of only type Dog (not including other animals):"
results.entries.each{|r| puts r.inspect }
 
# get all the cats again (specifically from Animal)
results = Animal.criteria.type("Cat")
puts "\n\nAnimal.criteria.type(\"Cat\") gives #{results.count} records of only type Cat (not including other animals):"
results.entries.each{|r| puts r.inspect }

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.