Skip to content

Instantly share code, notes, and snippets.

@JonKernPA
Created August 4, 2010 18:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JonKernPA/508525 to your computer and use it in GitHub Desktop.
Save JonKernPA/508525 to your computer and use it in GitHub Desktop.
This shows A User/Idea/Rating model using MongoMapper
class Idea
include MongoMapper::Document
key :brilliance, String, :default => "Dark Matter Sucks!"
many :ratings
belongs_to :user
key :user_id, ObjectId
def to_s
text = "#{user.name} had this IDEA: #{brilliance}\n\tRATINGS:\n"
ratings.each do |r|
text += "\t#{r.to_s}"
text += " [VAIN?]" if user == r.user
text += "\n"
end unless ratings.empty?
text
end
end
class Rating
include MongoMapper::Document
key :value, Integer, :default => 5
belongs_to :user
key :user_id, ObjectId
belongs_to :idea
key :idea_id, ObjectId
def to_s
"#{value} by #{user.name}"
end
end
Jon had this IDEA: Ducks walk like ducks. Duh
RATINGS:
2 by Fred
6 by Sally
Jon had this IDEA: Ducks talk like ducks. Duh
RATINGS:
3 by Fred
1 by Sally
1 by Jon [VAIN?]
require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
require 'rubygems'
require 'mongo'
connection = Mongo::Connection.new()
db = connection.db("mm-#{Rails.env}")
print "Connected to #{db.name}\n"
db.collection("User").drop # doesn't work????'
User.all.each {|r| r.destroy}
Idea.all.each {|r| r.destroy}
Rating.all.each {|r| r.destroy}
jon = User.create(:name => 'Jon')
fred = User.create(:name => 'Fred')
sally = User.create(:name => 'Sally')
jon_idea1 = Idea.create(:brilliance => "Ducks walk like ducks. Duh", :user => jon)
jon_idea2 = Idea.create(:brilliance => "Ducks talk like ducks. Duh", :user => jon)
rt1 = Rating.create( :idea => jon_idea1, :user => fred, :value => 2)
rt2 = Rating.create( :idea => jon_idea1, :user => sally, :value => 6 )
rt1 = Rating.create( :idea => jon_idea2, :user => fred, :value => 3)
rt2 = Rating.create( :idea => jon_idea2, :user => sally, :value => 1 )
rt2 = Rating.create( :idea => jon_idea2, :user => jon, :value => 1 )
Idea.all.each { |s| puts "#{s.to_s}\n" }
class User
include MongoMapper::Document
key :name, String, :default => "Albert"
many :ratings
many :ideas
def to_s
name
end
end
@JonKernPA
Copy link
Author

i ran the above from a rails project where the only changes needed were:

  1. add 'this to environment.rb
    config.gem "mongo_mapper"
  2. and create a simple one line mongo_config.rb under intializers
    MongoMapper.database = "todo-#{Rails.env}"
    Then my "scratchpad.rb" was under the test directory and it executed.

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