Skip to content

Instantly share code, notes, and snippets.

@JonKernPA
Created January 9, 2011 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonKernPA/771843 to your computer and use it in GitHub Desktop.
Save JonKernPA/771843 to your computer and use it in GitHub Desktop.
Company - Job example
class Company
include MongoMapper::Document
key :name, String
many :jobs
def to_s
name
end
def to_s_full
text = "#{name}"
unless jobs.empty?
text += "\n\tJOB LISTING\n"
jobs.each {|j| text += "\t#{j.to_s}\n"}
end
text
end
end
$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + "/../app/model")
require 'rubygems'
require 'mongo_mapper'
require 'company'
require 'job'
MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017)
MongoMapper.database = 'demo'
# Clean any data from prior runs
col = Company.all()
col.each {|c| c.destroy } unless col.nil?
col = Job.all()
col.each {|c| c.destroy } unless col.nil?
# Create some samples to show nesting
c1 = Company.create(:name => "Greatest Company Ever" )
j1 = Job.create( :description => "Agile Quarterback", :company => c1)
j2 = Job.create(:description => "MongoMapper Guru", :company => c1)
c1.reload
puts c1.inspect
puts j1
puts c1.to_s_full
puts "j1.company.jobs.size: #{j1.company.jobs.size}"
class Job
include MongoMapper::Document
key :description, String
# one :company # This does NOT work
key :company_id, ObjectId
belongs_to :company
def to_s
"#{company}: #{description}"
end
end
@JonKernPA
Copy link
Author

Structure

Files are in structure:
app/model
company.rb
job.rb
spec
company_demo.rb

Results

#<Company name: "Greatest Company Ever", title: nil, _id: BSON::ObjectId('4d29f2fb8951a2828c000001'), job_id: nil>

Greatest Company Ever: Agile Quarterback
Greatest Company Ever
    JOB LISTING
    Greatest Company Ever: Agile Quarterback
    Greatest Company Ever: MongoMapper Guru
j1.company.jobs.size: 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment