Skip to content

Instantly share code, notes, and snippets.

@mrinterweb
Created March 15, 2011 19:51
Show Gist options
  • Save mrinterweb/871322 to your computer and use it in GitHub Desktop.
Save mrinterweb/871322 to your computer and use it in GitHub Desktop.
Mongoid example of using references_many with an embedded class
I found this challenging to figure out so I thought I would share:
This shows how you can establish a references_many relationship to an embedded class. The limitation of course in my example is that when retrieving the ClientApplication's access_grants, it ends up retrieving User records. I believe this is a limitation of MongoDB in that MongoDB can not retrieve just embedded objects. It is not hard to accessing the embedded objects from the embedding class after retrieval.
I access users like this:
@client_app.users
This is an example of the mongo query:
hub_test['users'].find({"access_grants.client_application_id"=>BSON::ObjectId('4d7fbead9ebea474c0000012')}, {})
Finding the access_grants requires an accessor method in ClientApplication:
@client_app.access_grants
class AccessGrant
include Mongoid::Document
embedded_in :user, :inverse_of => :access_grants
referenced_in :client_application
end
class ClientApplication
require 'securerandom'
include Mongoid::Document
references_many :users,
:class_name => 'User',
:foreign_key => 'access_grants.client_application_id',
:inverse_of => :client_application
def access_grants
users.map { |u| u.access_grants.where(:client_application_id => id).all }.flatten
end
end
class User
include Mongoid::Document
embeds_many :access_grants
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment