mmcclannahan
mmcclannahan

Reputation: 1748

Mongoid Find Parent Object by Child Object ID

I have a residence object that contains users. However, in my application there is an edge case where the application will know the user but not the residence they are a member of. Is there a way to get the parent residence object based on a unique ID of a user?

class User 
    include Mongoid::Document

    field :email, type: String
    field :firstName, type: String
    field :lastName, type: String
end

class Residence
    include Mongoid::Document

    field :name, type: String
    field :updateTime, type: DateTime

    embeds_many :groceryLists
    embeds_many :events
    embeds_many :messages
    embeds_many :users
end

Something along the lines of:

user_id = foo
Residence.is_any(users._id: user_id)

Upvotes: 0

Views: 961

Answers (1)

Bashar Abdullah
Bashar Abdullah

Reputation: 1545

First I think class User should also have

embedded_in :Residence

Then just do

Residence.where('users._id'=> user_id).first

Upvotes: 2

Related Questions