I have models like bellow. i want to query events for user with different kind of statuses by guests 'list'. If am not wrong guests list should be embeded in events? If my model design are wrong i`m open for different solution.
class User
include Mongoid::Document
end
class Events
include Mongoid::Document
embeds_many :guests
end
Class Guests
include Mongoid::Document
embed_in :event
belongs_to :user
field :status
end
The model structure is wrong as in Mongo
you only keep the information in embedded documents which are required only in parent document.
If in guests you have only status field, then you can try this,e.g., two status type present or not present
class User
include Mongoid::Document
has_and_belongs_to_belongs_to :event, :inverse_of => "present_guests"
has_and_belongs_to_belongs_to :event, :inverse_of => "not_present_guests"
end
class Event
include Mongoid::Document
has_and_belongs_to_many :present_guests, :class_name => "User", :inverse_of => "present_guests"
has_and_belongs_to_has_many :not_present_guests, :class_name => "User", :inverse_of => "not_present_guests"
end
then you can query with the status like
Event.first.present_guests
I believe that model structure would work.
Here's an example query to get all events with guests with the 'waiting' status:
Events.where('guests.status' => 'waiting')
Here's another example to, given an event, get all that event's guests with 'waiting' status:
event = Events.first # get the desired event
event.guests.where(:status => 'waiting')
Finally, you should name your models singular names (User, Event, Guest). Also, your Guest model has some typos I fixed below:
class User
include Mongoid::Document
end
class Event
include Mongoid::Document
embeds_many :guests
end
class Guest
include Mongoid::Document
embedded_in :event
belongs_to :user
field :status
end