Skip to content

Instantly share code, notes, and snippets.

@chatgris
Created May 14, 2010 16:36
Show Gist options
  • Save chatgris/401354 to your computer and use it in GitHub Desktop.
Save chatgris/401354 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("mongoid_before_create")
end
Mongoid.master.collection("topics").drop
Mongoid.master.collection("members").drop
Mongoid.master.collection("posts").drop
class Topic
include Mongoid::Document
field :title
field :creator
embeds_many :members
embeds_many :posts
before_create :creator_as_members
protected
def creator_as_members
members << Member.new(:user => creator)
end
end
class Member
include Mongoid::Document
field :user
field :unread, :type => Integer, :default => 0
embedded_in :topic, :inverse_of => :members
validates_uniqueness_of :user
end
class Post
include Mongoid::Document
field :nickname
embedded_in :topics, :inverse_of => :posts
before_create :set_unread
protected
def set_unread
self.topics.members.each do |member|
member.unread += 1
end
end
end
@topic = Topic.create(:title => "Test", :creator => "chatgris")
Topic.where(:title => "Test").first.members.each do |member|
p member
end
p "----------------------"
@topic.posts.create(:nickname => "chatgris")
@topic.save
Topic.where(:title => "Test").first.members.each do |member|
p member
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment