Created
May 14, 2010 16:36
-
-
Save chatgris/401354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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