Skip to content

Instantly share code, notes, and snippets.

@burningTyger
Created December 27, 2011 15:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burningTyger/1523970 to your computer and use it in GitHub Desktop.
Save burningTyger/1523970 to your computer and use it in GitHub Desktop.
Mongomapper many to many associations with variable key names

If you're not familiar with Rails and ActiveRecord in general or with ActiveModel in particular then MongoMapper can be difficult to cope with at times. Even though the docs are fine and in detail some parts seem to be missing that are probably obvious for those coming from Rails. I'm not a Rails guy so I post my experience with many to many associations that might help one or the other save some precious debugging hours.

Take this code:

class User
  include MongoMapper::Document
  key :name, String, :required => true
  key :email, String

  key :post_ids, Array
  key :favourite_ids, Array

  many :posts, :in => :post_ids
  many :favourites, :class_name => 'Post', :in => :favourite_ids
end

class Post
  include MongoMapper::Document
  key :title, String, :required => true
  key :body, String
end

u = User.new{:name => "Joe"}
p = Post.new{:title => "My first post", :body => "Hello World"}

u.posts << p

This will work because I told MongoMapper which key collects the many associations for posts. This example is obvious because it's the same as in the docs. If you want to use the favorites you will have to tell MongoMapper which class you want to use. You cannot just make up a name and take it for granted that it'll work. A line like this:

many :favourites, :in => :favourite_ids

won't work because MM will look for a class called Favourite which does not exist. Be explicit and give a class name as in the original example. If you don't Mongomapper will raise an error saying that the BSON object cannot be serialzed into that key. Ver nasty to figure out if you think everything looks great.

@skylar
Copy link

skylar commented Jul 20, 2012

Thanks! As someone not familiar about AR, I was really wondering how to do this.

@burningTyger
Copy link
Author

you're welcome.

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