Using MongoDB with Ruby On Rails and the Mongomapper plugin
- by Micke
Hello, i am currently trying to learn Ruby On Rails as i am a long-time PHP developer so i am building my own community like page.
I have came pritty far and have made the user models and suchs using MySQL.
But then i heard of MongoDB and looked in to it a little bit more and i find it kinda nice.
So i have set it up and i am using mongomapper for the connection between rails and MongoDB.
And i am now using it for the News page on the site.
I also have a profile page for every User which includes their own guestbook so other users can come to their profile and write a little message to them.
My thought now is to change the User models from using MySQL to start using MongoDB.
I can start by showing how the models for each User is set up.
The user model:
class User < ActiveRecord::Base
has_one :guestbook, :class_name => "User::Guestbook"
The Guestbook model model:
class User::Guestbook < ActiveRecord::Base
belongs_to :user
has_many :posts, :class_name => "User::Guestbook::Posts", :foreign_key => "user_id"
And then the Guestbook posts model:
class User::Guestbook::Posts < ActiveRecord::Base
belongs_to :guestbook, :class_name => "User::Guestbook"
I have divided it like this for my own convenience but now when i am going to try to migrate to MongoDB i dont know how to make the tables.
I would like to have one table for each user and in that table a "column" for all the guestbook entries since MongoDB can have a EmbeddedDocument. I would like to do this so i just have one Table for each user and not like now when i have three tables just to be able to have a guestbook.
So my thought is to have it like this:
The user model:
class User
include MongoMapper::Document
one :guestbook, :class_name => "User::Guestbook"
The Guestbook model model:
class User::Guestbook
include MongoMapper::EmbeddedDocument
belongs_to :user
many :posts, :class_name => "User::Guestbook::Posts", :foreign_key => "user_id"
And then the Guestbook posts model:
class User::Guestbook::Posts
include MongoMapper::EmbeddedDocument
belongs_to :guestbook, :class_name => "User::Guestbook"
But then i can think of one problem.. That when i just want to fetch the user information like a nickname and a birthdate then it will have to fetch all the users guestbook posts. And if each user has like a thousand posts in the guestbook it will get really much to fetch for the system. Or am i wrong?
Do you think i should do it any other way?
Thanks in advance and sorry if i am hard to understand but i am not so educated in the english language :)