Skip to content

Instantly share code, notes, and snippets.

@jmaicher
Created February 22, 2011 15:28
Show Gist options
  • Save jmaicher/838833 to your computer and use it in GitHub Desktop.
Save jmaicher/838833 to your computer and use it in GitHub Desktop.
Querying embedded documents from embedded document
# ################
# Models
# ################
class Event
include Mongoid::Document
embeds_many :organizers, :class_name => "EventOrganizer"
end
class EventOrganizer
include Mongoid::Document
embedded_in :event, :inverse_of => :organizers
embeds_one :invitation
end
class Invitation
include Mongoid::Document
field :status, :type => String
embedded_in :event_organizer, :inverse_of => :invitation
end
# ################
# Query
# ################
# given an event with an organizer with an invitation with status "pending"
event.organizers.where({ "invitation.status" => "pending" }).first
# => nil
# ################
# Workaround
# ################
# Thanks to Durran (https://groups.google.com/group/mongoid/browse_thread/thread/bb36eae9f67fd324)
event.organizers.select { |org| org.invitation.status == "pending" }.first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment